//tslint:disable
import { async } from '@angular/core/testing';
import { Component, OnInit, NgZone, ViewChild, ElementRef, ChangeDetectorRef, ViewContainerRef, ComponentFactoryResolver } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup } from '@angular/forms';
import { typeWithParameters } from '@angular/compiler/src/render3/util';
import { PopoverController, IonSlides } from '@ionic/angular';
import { Platform, ModalController, AlertController, IonContent } from '@ionic/angular';

import { ActionSheetService, Modal, ModalService } from 'ng-zorro-antd-mobile';

import { EventService } from 'src/app/shared/service/event.service';
import { SharePageComponent } from 'src/app/coms/share-page/share-page.component';
import { MessageService } from 'src/app/shared/service/message.service';
import { RankingModalComponent } from 'src/app/coms/ranking-modal/ranking-modal.component';

import { ComItem } from '../com-item';
import { ChooseCityComponent } from '../../../coms/choose-city/choose-city.component';
import { AppGlobalService } from '../../../shared/service/app-global.service';
import { HttpService } from '../../../shared/service/http.service';
import { MapBaiduService } from '../../../shared/service/map.baiduapi';
import { TabsService } from './../../../shared/service/tabs.service';
import { PageModalService } from './../../../shared/service/page-modal-service';
import { RecommendModalComponent } from 'src/app/coms/recommend-modal/recommend-modal.component';
import { ShowPhoneModalComponent } from 'src/app/coms/show-phone-modal/show-phone-modal.component';
import { NewInquiryPageModalComponent } from 'src/app/coms/new-inquiry-page-modal/new-inquiry-page-modal.component';
import { NestedFormTagComponent } from 'src/app/coms/nested-form-tag/nested-form-tag.component';
import { ModalFromCenterLeave, ModalFromCenterEnter } from 'src/app/utils/transitions';
import { PopoverComponent } from '../../../coms/popover/popover.component';
import { ChatService } from 'src/app/shared/service/chatService';
import { StoreConsultantComponent } from 'src/app/coms/store-consultant/store-consultant.component';
declare let $: any;
declare let wx: any;

@Component({
  selector: 'app-nav-one',
  templateUrl: '../entry.page.html',
  styleUrls: ['../entry.page.scss']
})
export class NavOneComponent implements OnInit {
  @ViewChild("segment", { read: ElementRef }) private segment: ElementRef;
  hidden = false;
  selectedIndex: number;
  menusBar: any;
  isHeader = true;
  coms: ComItem[];
  headerComs: ComItem[];
  subComs: ComItem[];
  footerComs: ComItem[];
  forward: any; // 路由对象
  targetUrl: string;  // 请求路径
  // 标签头数据
  titleBar: any = {};
  isGrayBg = false; // 默认背景为灰色
  bgCssStyle = ''; // 默认背景为灰色
  isPageDisabled = false;
  backgroundImg: string; // 头部背景图片
  showWaterImg = false; // 是否显示水印
  showRefresher = false; // 是否可以下拉刷新
  showLoading = false; // 是否展示上拉动画
  showScrollToTopBtn = false;// 是否展示滚动到顶部按钮。
  showScrollToTopBtnTemp = false;// 是否展示滚动到顶部按钮。
  isAddCommonNestedTag = true;
  // 位置对象
  positionInfo: any = {};



  showTopTab = false; // 是否显示顶部tab
  showSubTab = false; // 是否显示Subtab
  showEmptyMessage = false; // 是否显示暂无消息
  subTagData: any; // 顶部tab data
  switchBlockTag: any; // 蜂喔app新增首页tag样式
  subAWidth: string;
  tagData: any;
  aWidth: string;
  openBackdrop: boolean;
  showRefresh = false; // 是否显示刷新
  netState: any; // 网络状态
  shareData: any; // 分享页面数据
  isShowingTipsDiv = false;
  isShowingAlertDiv = false;
  pageDataFirstTag: any = {};
  isScrolling = false;
  appTypeCustom: any;
  appTabTypeCustom: any;
  private timer: any;
  showDivTips = false;
  showSwitchBlockTag = false;
  tData = {
    customer: [{
      avatar: "http://www.xx.com/xx.png",
      name: "小明",
      submit: {
        id: "string",
        content: {}
      }
    }],
    moreCustomer: {
      label: "更多客户",
      link: {
        type: "page",
        target: "pageId",
        params: {}
      }
    },
    copy: {
      label: "复制链接",
      content: "url"
    },
    savePic: {
      label: "保存图片"
    }
  };
  selectedSegment = 0;
  options_: any; //控制轮播图
  idx = 0;
  addressShow = false;//是否显示地址下半部分
  // this.footerComs[0].tagData.data[0].label="1"
  isRefreshAfterCLickSwitchButton = false;
  refreshFilterId = "";
  tabBarUnderlineStyle: any;
  currentDataArray = [];
  tabPaneIndex = 0;
  isSpinning = false;
  keyword: any;
  currentRootTabId = new Date().getTime();
  @ViewChild('superCotainer') scrollContent: ElementRef;
  @ViewChild('scrollContent') scrollContentDiv: ElementRef;
  @ViewChild(IonContent) content: IonContent;
  @ViewChild('slidesBy') slides: IonSlides;
  @ViewChild('slideNewsarousel') slides2: IonSlides;
  @ViewChild('viewContainer', { read: ViewContainerRef }) viewContainerRef: ViewContainerRef;
  firstRowLeftIconBtnTimestemp = '';
  serviceLink: any;

  //2.0新增 小区位置信息
  areaPositionInfo: any;
  isStickyDiv1 = false; // 2.0 
  isSearchBottomDiv1 = false; // 2.0 
  isStickyTabLocation = false; // 2.0.3

  headerBgStyle: any; //2.0.1
  headerStyle: any;// 2.0.1 
  needScrollToTopHiddenImg = false;
  isHearderDivInConent = false;
  // 2.2.8 add ulDivID 
  subTagDataId = 'subTagData';
  switchNewCssBtnId = 'switchNewCssBtnId';
  switchBlockTagClassNameType = 0; // 默认为0  newCss 当为newCss2时为1
  private refreshDataTime = 0;
  refreshDelayTime = 0;
  currentFixedTagArray = [];// 2023.12.13 缓存切换的tagdata
  dynamicComponent: any;
  constructor(
    private platform: Platform,
    private http: HttpService,
    public router: Router,
    public appGlobalService: AppGlobalService,
    public pageModalService: PageModalService,
    private modalController: ModalController,
    private mapBaiduService: MapBaiduService,
    private tabsService: TabsService,
    private eventService: EventService,
    private chatService: ChatService,
    public alertController: AlertController,
    private ngZone: NgZone,
    private actionSheet: ActionSheetService, // 必须有
    private modalService: ModalService,
    private message: MessageService,
    private ref: ChangeDetectorRef,
    public popoverController: PopoverController,
    private resolver: ComponentFactoryResolver
  ) {



    // 有customerTab时切换
    this.eventService.eventEmit.on("nav1ScrollToBottom", (obj) => {
      const reqTag = localStorage.getItem('nav1ScrollToBottomTag');
      if (reqTag !== undefined) {
        localStorage.removeItem('nav1ScrollToBottomTag');
        // tslint:disable-next-line:radix
        this.content.scrollByPoint(0, parseInt(reqTag), 500);
        // this.content.scrollToBottom(0);
      }
    });

    // 页面包含appTab，调用part接口刷新navOne的footerComs
    this.eventService.eventEmit.on("nav1UpdateFooterComs", (obj) => {
      const reqTag = localStorage.getItem('nav1UpdateFooterComsTag');
      if (reqTag !== undefined) {
        localStorage.removeItem('nav1UpdateFooterComs');
        this.tabsService.getPageData(obj, pageData => {
          this.footerComs = pageData.footerComs;
        });
      }
    });



    // 安卓禁用物理返回键之后手动触发返回
    this.eventService.eventEmit.on("nav1ManualBack", async (obj) => {
      console.log('msg----->nav1ManualBack time=' + JSON.stringify(new Date().toLocaleTimeString()));
      const reqTag = localStorage.getItem('nav1ManualBackTag');
      localStorage.removeItem('nav1ManualBackTag');
      if (reqTag !== undefined && reqTag === '1') {
        localStorage.setItem('nav1ManualBackTag', '2');
        //2024.01.12 新增返回关闭弹窗处理
        const modal = await this.modalController.getTop();
        if (modal) {
          modal.dismiss();
          return;
        } else {
          if (this.appGlobalService.showExit()) {
            return;
          }


          if (this.pageDataFirstTag.disableBack === undefined && !this.isShowingTipsDiv && !this.isShowingAlertDiv) {
            this.back();
          }
        }
      }
    });

    // 安卓禁用物理返回键之后手动触发返回
    this.eventService.eventEmit.on("nav1ManualBack1", async (obj) => {
      const reqTag = localStorage.getItem('nav1ManualBackTag1');
      localStorage.removeItem('nav1ManualBackTag1');
      if (reqTag !== undefined) {
        //2024.01.12 新增返回关闭弹窗处理
        const modal = await this.modalController.getTop();
        if (modal) {
          modal.dismiss();
          return;
        } else {
          this.back();
        }
      }
    });

    // 2023.05.05 修复保姆·月嫂店上滑异常
    this.eventService.eventEmit.on("refreshNavOneTreeView", (obj) => {
      console.log('refreshNavOneTreeView', new Date().toLocaleTimeString());
      this.appGlobalService.refreshViewTree(this.content);
    });
  }

  ngOnInit() {
    this.appGlobalService.coms = [];
    this.appGlobalService.pageId = '';
    const forward =  this.appGlobalService.getCurrentTarget();
      if(forward && forward.pageId){
        this.appGlobalService.pageId = forward.pageId
      }
    window['tabs'] = this.tabsService;
    console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  	thisid=  ', this.currentRootTabId);
    this.subTagDataId += new Date().getTime();
    this.switchNewCssBtnId += new Date().getTime();
    // 清空底部按钮 
    this.appGlobalService.footerButton = undefined;
    // 删除顶部筛选
    this.appGlobalService.headerSiftTag = undefined;
    this.appGlobalService.headerTopTab = undefined;
    // 1.7.0 新增参数
    this.firstRowLeftIconBtnTimestemp += new Date().getTime();
    const bodyStyles = window.getComputedStyle(document.body);
    this.appTypeCustom = bodyStyles.getPropertyValue('--appTypeCustom').trim().replace('"', '').replace('"', '');
    this.appTabTypeCustom = bodyStyles.getPropertyValue('--appTabTypeCustom').trim().replace('"', '').replace('"', '');
    this.openBackdrop = this.appGlobalService.openBackdrop;
    this.forward = this.appGlobalService.getCurrentTarget();
    this.getInitInfo(0);
    // 搜索页面更多action/ 发布页面新增Navbtn
    if (this.eventService.eventEmit.listenerCount('searchType100') > 0) {
      this.eventService.eventEmit.removeListener('searchType100');
    }
    this.eventService.eventEmit.on('searchType100', item => {
      this.selectItem(item);
    });
    if (this.eventService.eventEmit.listenerCount('refreshPageData' + localStorage.getItem('currentPath')) > 0) {
      this.eventService.eventEmit.removeListener('refreshPageData' + localStorage.getItem('currentPath'));
    }

    this.eventService.eventEmit.on('refreshPageData' + localStorage.getItem('currentPath'), pageData => {



      console.log('nav one  need Refresh page data 刷新页面 ------->\n');
      console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  	刷新页面thisid=   ', this.currentRootTabId);
      const tempForward = this.appGlobalService.getCurrentTarget();
      if (tempForward && tempForward.params && tempForward.params.useSelectedPosition) { // 配置了才更新
        this.positionInfo = JSON.parse(this.mapBaiduService.getStore('position'));
        const lng = this.appGlobalService.getAddressLng ? this.appGlobalService.getAddressLng : tempForward.params.longitude;
        const lat = this.appGlobalService.getAddressLat ? this.appGlobalService.getAddressLat : tempForward.params.latitude;
        this.appGlobalService.searchShopLat = lat;
        this.appGlobalService.searchShopLng = lng;
        console.log('searchShopPoint', 'lng' + lng + ',lat' + lat);
        this.eventService.eventEmit.emit('getAddressByPoint', '' + lng + ',' + lat);

      }
      this.coms = pageData.coms;
      this.headerComs = pageData.headerComs;
      this.subComs = pageData.subComs;
      this.titleBar = pageData.titleBar;
      this.appGlobalService.coms = this.coms;
      // 2023.11.04-如果我的物业tab包含imagesTag标签则赋值新筛选tag
      if (this.coms
        && this.coms[0]
        && this.coms[0].tagData
        && this.coms[0].tagData.name === 'imagesTag') {
        this.appGlobalService.consoleLog("tagData.name === 'imagesTag", '  	   ');
        
        this.subComs = this.coms;
        this.coms = undefined;
        this.showSubTab = true;
        this.showTopTab = false;
        this.subTagData = this.subComs[0].tagData;

        if (this.subTagData && this.subTagData.length > 0) {
          this.subTagData.sort((a, b) => { return a.indexTab - b.indexTab; });
        }
        // this.refreshNav1FixedContainer();
      } else {
        this.showSubTab = false;
      }
      if (this.titleBar
        && this.titleBar.link
        && this.titleBar.link.link
        && this.titleBar.link.link.params
        && this.titleBar.link.link.params.useCityIdLabel === ''
      ) {
        this.titleBar.link.link.params.useCityIdLabel = JSON.parse(localStorage.getItem('currentCityPosition')).name;
      }

      console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  	   ', this.titleBar);
      this.footerComs = pageData.footerComs;
      this.isGrayBg = pageData.isGrayBg;
      this.bgCssStyle = pageData.bgCssStyle;
      this.isPageDisabled = pageData.disabled;
      this.showRefresher = pageData.showRefresher;
      this.showRefresh = false;
      this.showLoading = pageData.showLoading;
      this.backgroundImg = pageData.backgroundImg;
      this.showWaterImg = pageData.showWaterImg;

      this.getCurrentToggleData();
      // 2023.05.05 蜂喔商户处理submit之后滑动异常。导致第一次点击没有显示tab选项卡
      // 2023.05.05 初始化请求参数 that.isStickyTabLocation
      this.isStickyTabLocation = false;
      this.appGlobalService.refreshViewTree(this.content);
    });
    this.eventService.eventEmit.on('addFooterCom', coms => {
      if (coms) {
        this.footerComs.push(coms);
      } else {
        this.footerComs = [];
      }

    });
    this.ngZone.runOutsideAngular(() => {
      this.ngZone.run(() => {
        this.eventService.eventEmit.on('testRefreshFooterComsContainer', () => {
          const askTag = localStorage.getItem("refreshFooterComsTag");
          if (askTag !== null) { this.loadComponent(askTag); }
        });
      });
    });

    this.options_ = {
      direction: 'vertical',
      initialSlide: 0,
      slidesPerView: 1,
      autoplay: {
        delay: 3000,
      },
      speed: 200,
      autoplayDisableOnInteraction: false,
      loop: true,
      slidesperview: true,
    };

    const targetObj = JSON.parse(localStorage.getItem('targetObj'));
    if (targetObj && targetObj.bat && targetObj.bat.length > 0) {
      targetObj.forward = targetObj.bat[targetObj.bat.length - 1];
      console.log('当前page------> targetObj.forward:', targetObj.forward);
      targetObj.forward['currentRootTabId'] = this.currentRootTabId;
      localStorage.setItem('targetObj', JSON.stringify(targetObj));
    }

    if (this.appGlobalService['useDefaultCityPostion'] !== undefined) {
      this.areaPositionInfo =
      {
        address: "",
        center: this.appGlobalService.defaultCityCenter,
        code: this.appGlobalService.defaultCityId,
        name: this.appGlobalService.defaultCityName,
        district: this.appGlobalService.defaultDistrictName,
        location: this.appGlobalService.defaultCityCenter
      };
    } else {
      this.areaPositionInfo =
      {
        address: "",
        center: localStorage.getItem('mapPosition') ? JSON.parse(localStorage.getItem('mapPosition')).center : this.appGlobalService.defaultCityCenter,
        code: localStorage.getItem('mapPosition') ? JSON.parse(localStorage.getItem('mapPosition')).code : this.appGlobalService.defaultCityId,
        name: localStorage.getItem('mapPosition') ? JSON.parse(localStorage.getItem('mapPosition')).name : this.appGlobalService.defaultCityName,
        district: localStorage.getItem('mapPosition') ? JSON.parse(localStorage.getItem('mapPosition')).district : this.appGlobalService.defaultDistrictName,
        location: localStorage.getItem('mapPosition') ? JSON.parse(localStorage.getItem('mapPosition')).location : this.appGlobalService.defaultCityCenter
      };
    }

    this.appGlobalService.showfloatShoppingCart(false);

  }


  // 2024.06.03
  needRefreshTabByEventEmit() {
    if (this.tabsService.tabPage.indexOf("tab") > -1) {
      const tab = this.tabsService.tabPage;
      const tabIndex = tab.substring(tab.length - 1);
      console.log("needRefreshTab" + tabIndex);
      localStorage.setItem('needRefreshTab' + tabIndex, 'true');
      this.eventService.eventEmit.emit(this.tabsService.tabPage, '1');
      console.log('submit back-eventEmit--->' + this.tabsService.tabPage);
    }
  }


  sendShareIdToWx() {

    // if ((typeof wx) !== 'undefined') {
    //   wx.miniProgram.getEnv((res) => {
    //       if (res.miniprogram) {
    //         const path = '/pages/session/session?shareLink='+encodeURIComponent("http://zeno-pay-fengwo.xwkj.local/h?id=a4afbfeabbf82e3a29e4a83f1569c626")
    //         wx.miniProgram.navigateTo({url: path});
    //       //   wx.miniProgram.navigateBack({delta: 1})
    //       //   // 发送消息给小程序
    //       // wx.miniProgram.postMessage({data : encodeURIComponent("http://zeno-pay-fengwo.xwkj.local/h?id=a4afbfeabbf82e3a29e4a83f1569c626") });

    //       }
    //   });
    // }

    if (this.titleBar && this.titleBar.shareUrl && this.titleBar.shareUrl.length > 0) {

      if ((typeof wx) !== 'undefined') {
        wx.miniProgram.getEnv((res) => {
          if (res.miniprogram) {
            let path = '/pages/session/session?shareLink=' + encodeURIComponent(this.titleBar.shareUrl)
            if (this.titleBar.shareTitle && this.titleBar.shareTitle.length > 0) {
              path = path + encodeURIComponent("&shareTitle=" + this.titleBar.shareTitle)
            }

            wx.miniProgram.navigateTo({ url: path });
          }
        });
      }
    }


  }
  loadComponent(askTag) {
    this.footerComs = [];
    const tag = JSON.parse(askTag);
    if (!tag.clean) {
      if (Array.isArray(tag)) {

        for (let index = 0; index < tag.length; index++) {
          const element = tag[index];
          this.tabsService.getComsDataByStyle(element.style, callData => { if (callData) { this.footerComs.push(callData); } }, element);
        }
      } else {
        this.tabsService.getComsDataByStyle(tag.style, callData => { if (callData) { this.footerComs.push(callData); } }, tag);
      }

    }
    this.eventService.eventEmit.emit("loadFooterComponent", this.footerComs);
    // localStorage.removeItem("refreshFooterComsTag");
  }

  getInitInfo(index?, pageId?) {
    try {

      let newFilterTagDefaultIndex = "0";
      this.positionInfo = JSON.parse(this.mapBaiduService.getStore('position'));

      if (this.forward !== null) {
        if (this.forward && this.forward.params && this.forward.params.index) {
          newFilterTagDefaultIndex = this.forward.params.index;
        }
        if (this.forward && this.forward.params && this.forward.params.returnAddressIdKey) {
          this.selectAddress();
        }
        this.forward.params = (pageId && index) ? ({ code: this.positionInfo.code }) : this.forward.params;
        // 确保每次是最新的sessionId
        if (localStorage.getItem("sessionId")) {
          this.forward.sessionId = localStorage.getItem("sessionId")
        }
        // 蜂喔商户2.1.0 销售中土特管理tab切换指定选中
        if (this.forward.params && this.forward.params.needCheckAndReplaceIndexTab !== undefined) {
          if (this.appGlobalService[this.forward.params.needCheckAndReplaceIndexTab] !== undefined && this.forward.params.indexTab !== undefined) {
            this.forward.params.indexTab = this.appGlobalService[this.forward.params.needCheckAndReplaceIndexTab];
          }
        }

        // 蜂喔2.2.8 2023年9月22日新增用于计算districtCode
        if (this.forward && this.forward.params && this.forward.params.calculateDistrictCode !== undefined) {
          let position = JSON.parse(localStorage.getItem("position"));
          if (position && position.districtCode) {
            this.forward.params.calculateDistrictCode = position.districtCode;
          }
        }
        console.log('this.forward.params.useSelectedPosition:' + this.forward.params.useSelectedPosition);
        // 2.2.19 
        if (this.forward
          && this.forward.params
          && this.forward.params.useSelectedPosition !== undefined
          && this.forward.params.useSelectedPosition === 'true') {
          if (this.appGlobalService.getAddressLng) {
            console.log('use choose address 1' + this.appGlobalService.getAddressLng);
            this.forward.params.longitude = this.appGlobalService.getAddressLng;
            console.log('use choose address 2' + this.forward.params.longitude);
          }
          if (this.appGlobalService.getAddressLat) {
            console.log('use choose address 3' + this.appGlobalService.getAddressLat);
            this.forward.params.latitude = this.appGlobalService.getAddressLat;
            console.log('use choose address 4' + this.forward.params.latitude);

          }
        }
        console.log('use choose address 5' + this.forward.params.longitude);

        this.http.post('application/page', this.forward, res => {
          this.showRefresh = false;
          if (res.code === -1000 && res.message && res.message.length > 0) {
            this.titleBar = {
              background: 'white',
              back: { layout: 'left' },
              errMessage: res.message
            };
            this.showRefresh = true;
          }




          // add by andrew.wen for bug-view-3853.html
          if (newFilterTagDefaultIndex && newFilterTagDefaultIndex !== "0") {
            // 如果为newFilterTag且开启检查默认值
            if (res.script.includes('"style":"newFilterTag",') && res.script.includes('"checkDefaultValue":true')) {
              res.script = res.script.replace('"style":"newFilterTag",', '"style":"newFilterTag","defaultBusinessStatusIndex":"2",');
            }
          }
          let pageData = JSON.parse(res.script);

          // 2023.11.14
          if (pageData.refreshDelayTime) {
            this.refreshDelayTime = parseInt(pageData.refreshDelayTime);
            console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  refreshDelayTime=	   ', this.refreshDelayTime);
          }

          // 如果需要记录上一次操作参数则添加新配置重新拼装请求参数然后发送page。
          if (res.script.includes('"style":"tag.FilterTagLogic",') && res.script.includes('"needRememberLast":true')) {
            const filterTagName = 'needRememberResult' + pageData.views[0].tags[0].name;
            if (localStorage.getItem(filterTagName)) {
              pageData.views[0].tags[1].data.data = [];
              res.script = JSON.stringify(pageData);
            }
          }
          // 检查新跳转的页面是否需要自动填充
          if (res.script.includes('"style":"tag.AppTabTagLogic",') && res.script.includes('"name":"exactCommendTag",')) {
            pageData = {};
            res.script = res.script.replace('"name":"exactCommendTag",', '"name":"exactCommendTag","isAutoFillData":true,');
            pageData = JSON.parse(res.script);
          }

          // 检查新跳转的页面是否需要自动填充地址ID
          if (res.script.includes('tag.AppSimpleDetailTagLogic') && res.script.includes('type6linkParamsAppendAddressId')) {
            this.appGlobalService.needAppendAddressId = true;
          }

          // 检查新跳转的页面是否需要自动填充地址ID
          if (res.script.includes('tag.AppSimpleDetailTagLogic') && res.script.includes('needScrollToTopHiddenImg')) {
            this.needScrollToTopHiddenImg = true;
          }
          // 是否需要更新viewId 
          if (res.script.includes('"style":"page.FramePageLogic",') && res.script.includes('"clientType":"js",')) {
            console.log('refreshViewId');
            localStorage.setItem("appNav", JSON.stringify(pageData.navgtion));
          }
          // 检查新跳转的页面是否需要手动隐藏
          if (res.script.includes('"style":"tag.MessageWheelTagLogic",') && res.script.includes('"style":"tag.FilterTagLogic",')
            && res.script.includes('needHiddenId')
          ) {
            const headerTag = pageData.views[0].tags[0];
            // console.log('msg----->', headerTag.additional.needHiddenId);
            pageData = {};
            res.script = res.script.replace('"style":"tag.FilterTagLogic",', '"style":"tag.FilterTagLogic","needHiddenId":"' + headerTag.additional.needHiddenId + '",');
            pageData = JSON.parse(res.script);
          }

          // 1.7.0 赚钱宝新增按钮参数
          if (res.script.includes('"style":"appLjCaseListTag",') && res.script.includes('"firstRowLeftIconBtn"')) {
            pageData = {};
            res.script = res.script.replace('"firstRowLeftIconBtn"', '"' + this.firstRowLeftIconBtnTimestemp + '"');
            pageData = JSON.parse(res.script);
          }

          if (res.script.includes('"style":"tag.AppOppDetailTagLogic",') && res.script.includes('"disabled":true,')) {
            const len = pageData.views[0].tags.length - 1;
            if (pageData.views[0].tags[len].style === 'tag.PhoneTagLogic') {
              pageData.views[0].tags.pop();
              pageData.views[0].tags.pop();
              pageData.views[0].tags.pop();
              const tempTags = pageData.views[0].tags;
              pageData.views[0].tags = tempTags;
              res.script = JSON.stringify(pageData);
            }
          }



          // 1.7.1 赚钱宝检测是否有搜索框
          if (res.script.includes('"style":"tag.AppSimpleDetailTagLogic",') && res.script.includes('"cssType":"18-search-it"')) {
            const len = pageData.views[0].tags.length - 1;
            for (let index = 0; index < len; index++) {
              const element = pageData.views[0].tags[index];
              if (element.style === 'tag.AppSimpleDetailTagLogic') {
                if (pageData.titleBar && pageData.titleBar.searchInput) {
                  element.searchInput = pageData.titleBar.searchInput;
                  break;
                }
              }
            }
            res.script = JSON.stringify(pageData);
          }

          // 2.3.3 
          if (res.script.includes('"style":"tag.AppSimpleDetailTagLogic",') && res.script.includes('"cssType":"60-expressOrderBtn"')) {


            const len = pageData.views[0].tags.length - 1;
            for (let index = 0; index < len; index++) {
              const element = pageData.views[0].tags[index];
              if (element.style === 'tag.AppSimpleDetailTagLogic' && element.data.cssType === '60-expressOrderBtn') {
                this.viewContainerRef.clear();
                const factory = this.resolver.resolveComponentFactory(StoreConsultantComponent);
                const componentRef = this.viewContainerRef.createComponent(factory);
                element.data.cssType += 'New';// 2024.06.20 修复出现反复创建的问题
                (componentRef.instance).tagData = element;
                pageData.views[0].tags[index] = null;
                break;
              }
            }
            res.script = JSON.stringify(pageData);



          }

          // 1.6.25 新增折叠手风琴推荐列表
          if (res.script.includes('"style":"tag.AppSimpleDetailTagLogic",') && res.script.includes('"cssType":"30-accordionList"')) {
            const len = pageData.views[0].tags.length;
            let ele1;
            let ele2;
            let index1;
            let index2;
            for (let index = 0; index < len; index++) {
              const element = pageData.views[0].tags[index];
              if (element.style === 'tag.AppSimpleDetailTagLogic' && element.data.cssType === '30-accordionList') {
                ele1 = element;
                index1 = index;
              } else if (element.style === 'appGeneralListTag' && element.name.includes('_innerAccordionList')) {
                ele2 = element;
                index2 = index;
              } else if (element.style === 'orderInfoListTag' && element.name.includes('_innerAccordionList')) {
                ele2 = element;
                index2 = index;
              }
            }
            if (ele1 && ele2) {
              ele1['recommendListData'] = ele2;
              pageData.views[0].tags[index1] = ele1;
              pageData.views[0].tags[index2] = { type: 'tag', style: 'un-resevole-tag' };
            }
            res.script = JSON.stringify(pageData);
          }

          // 检查是否有AppTabTag是否有callPhone的footer
          // tslint:disable-next-line:max-line-length
          // if (res.script.includes('"style":"tag.AppTabTagLogic",') && res.script.includes('"style":"tag.PhoneTagLogic","name":null,"linearLayout":"footer"')) {
          //   pageData = {};
          //   pageData = JSON.parse(res.script);
          //   const viewTagsLen = pageData.views[0].tags.length;
          //   const appTabTag = pageData.views[0].tags[viewTagsLen - 1];
          //   const footerTag = appTabTag.currentData.tags.pop();
          //   pageData.views[0].tags.push(footerTag);
          //   res.script = JSON.stringify(pageData);
          // }


          // 回到 主tab
          if (pageData.style === 'page.FramePageLogic') {
            console.log('nav to home page')
            // 清除访问历史
            // 修复http://chandao.xwkj.local:8018/bug-view-4320.html
            this.appGlobalService.popAllTarget();
            // history.go(-(localStorage.getItem('lastNavIndex')));
            localStorage.setItem("needRefreshTab1", "true");
            localStorage.setItem("needRefreshTab2", "true");
            localStorage.setItem("needRefreshTab3", "true");
            localStorage.setItem("needRefreshTab4", "true");
            localStorage.setItem("needRefreshTab5", "true");
            setTimeout(() => {
              this.router.navigate(['/home/tab1'], { queryParams: {}, replaceUrl: true });
            }, 100);

          }

          // 请求数据成功
          if (res) {
            if (res !== undefined && res != null) {
              this.tabsService.getPageData(res, async pageData => {
                this.footerComs = pageData.footerComs;
                this.headerComs = pageData.headerComs;
                this.coms = pageData.coms;
                if (this.coms[0] && this.coms[0].tagData.style === 'tag.AppTabTagLogic' && this.coms[0].tagData.name === 'homeAppTabTag') {
                  this.showTopTab = true;
                  this.tagData = this.coms[0].tagData;
                  this.aWidth = 100 / this.tagData.data.length + '%';
                }
                if (this.coms[0] && this.coms[0].tagData.style === 'tag.AppTabTagLogic' && this.coms[0].tagData.name === 'imagesTag') {
                  this.subComs = this.coms;
                  this.coms = undefined;
                  this.showSubTab = true;
                  this.showTopTab = false;
                  this.subTagData = this.subComs[0].tagData;
                  // this.refreshNav1FixedContainer();
                  // 2024.09.24 新增使用part接口的参数作为局部刷新时请求part接口的参数，例如销售推广中的商机入口-》转让
                  if (this.subTagData.data[0].partLink.params.usePartParamsForAjaxRefresh) {
                    this.appGlobalService.currentPartParams = this.subTagData.data[0].partLink.params;
                  }

                  if (this.subTagData && this.subTagData.length > 0) {
                    try {
                      this.subTagData.sort((a, b) => { return a.indexTab - b.indexTab; });
                    } catch (error) {
                      this.subTagData.data.sort((a, b) => { return a.indexTab - b.indexTab; });
                    }
                  }


                  this.selectedSegment = +this.subTagData.currentTab;
                  this.currentDataArray = new Array(this.subTagData.data.length);
                  if (this.subTagData.currentData) {
                    this.currentDataArray[this.tabPaneIndex] = this.subTagData.currentData.tags;
                  }

                  this.appGlobalService.consoleLog('设置subTagData的数组的currentData', '  	   ');
                  // 2024.10.24 14:53
                  window['appGlobalService'].loadFixedTabCallBack=(obj)=>{
                    this.refreshNav1FixedContainer();
                  };
                  this.tabBarUnderlineStyle = { border: '1px solid #ffca3a', bottom: '4px', background: '#0A3CA0', width: '2rem' };
                  this.tabBarUnderlineStyle['margin-left'] = 'calc(( 100vw / ' + this.subTagData.data.length + '  - 2.5rem) * 0.5)';
                  this.subAWidth = 100 / this.subTagData.data.length + '%';
                  // 如果我的物业tab包含筛选新标签则赋值新筛选tag
                  if (this.subComs[0] && this.subComs[0].tagData.currentData && this.subComs[0].tagData.currentData.tags[0].name === 'switchBlockTag') {
                    this.switchBlockTag = this.subComs[0].tagData.currentData.tags.shift();
                   
                    console.log('this.switchBlockTag 1');
                    if (this.switchBlockTag) {
                      window['appGlobalService'].loadSwitchBtnPicCallBack = (obj) => {
                        this.appGlobalService.consoleLog('loadSwitchBtnPicCallBack', '  	   ');
                        //  2024.07.16 新增 服务入口
                        if (this.switchBlockTag.data
                          && Array.isArray(this.switchBlockTag.data)) {
                          for (let j = 0; j < this.switchBlockTag.data.length; j++) {
                            const element = this.switchBlockTag.data[j];
                            if (j !== 0 && element.selected && element.selected === "true") {
                              const selectId = this.currentRootTabId + element.id;
                              if (document.getElementById(selectId)) {
                                document.getElementById(selectId).scrollIntoView({
                                  behavior: "smooth",
                                  inline: "center",
                                  block: "nearest"
                                });
                              }
                              break;
                            }
                          }
                        }
                      };


                      if (this.switchBlockTag
                        && this.switchBlockTag.data
                        && this.switchBlockTag.data[0]
                        && this.switchBlockTag.data[0].needCheckTabName) {

                        if (!this.appGlobalService.needCheckTabName) {
                          this.appGlobalService.needCheckTabName = this.switchBlockTag.data[0].needCheckTabName;
                          if (this.switchBlockTag.data[0] && this.switchBlockTag.data[0][this.appGlobalService.needCheckTabName]) {
                            this.appGlobalService[this.appGlobalService.needCheckTabName] = this.switchBlockTag.data[0][this.appGlobalService.needCheckTabName];
                          }
                        }
                      }

                      if (this.switchBlockTag.style === 'newCss2') {
                        this.switchBlockTagClassNameType = 1;
                      }
                      this.processSwitchBlockTag();
                    }
                  }
                  let len;
                  this.subComs[0].tagData.currentData ? len = this.subComs[0].tagData.currentData.tags.length - 1 : '';
                  if (!isNaN(len)
                    && this.subComs[0]
                    && this.subComs[0].tagData.currentData.tags[len].style === "tag.AppGeneralButtonTagLogic") {
                    this.isRefreshAfterCLickSwitchButton =
                      (this.subComs[0].tagData.currentData.tags[len]
                        && this.subComs[0].tagData.currentData.tags[len].id !== undefined);
                    if (this.subComs[0].tagData.currentData.tags[len]
                      && this.subComs[0].tagData.currentData.tags[len].id !== undefined) {
                      this.refreshFilterId = this.subComs[0].tagData.currentData.tags[len].id;
                    }
                  }
                }

                // 新房出售列表新增筛选按钮 TODO
                if (
                  this.headerComs[0] && this.headerComs[0].tagData.style === 'tag.FilterTagLogic'
                  && this.coms.length > 0 && this.coms[0].tagData.style === 'siftSwitchBlockTag') {
                  this.headerComs[0].tagData.switchBlockTag = this.coms[0].tagData;
                }
                this.titleBar = pageData.titleBar;
                if (this.titleBar
                  && this.titleBar.position
                  && this.titleBar.position.link
                  && this.titleBar.position.link.param
                  && this.titleBar.position.link.param[0]
                  && this.titleBar.position.link.param[0].name === 'useSelectedPosition') {
                  this.positionInfo.locationDescribe = this.appGlobalService.callBackFunctionOnGetAddressByPoint;
                  this.appGlobalService.refreshViewTree(this.content);
                }
                // 页面包含appTab，调用part接口刷新navOne的footerComs
                if (this.titleBar
                  && this.titleBar.link
                  && this.titleBar.link.link
                  && this.titleBar.link.link.params
                  && this.titleBar.link.link.params.useCityIdLabel === ''
                ) {
                  this.titleBar.link.link.params.useCityIdLabel = JSON.parse(localStorage.getItem('currentCityPosition')).name;

                }
                // 2.0.1 新增
                if (this.titleBar && this.titleBar.headerBgStyle !== undefined) {
                  this.headerBgStyle = this.titleBar.headerBgStyle;
                }
                // 2.0.1 新增
                if (this.titleBar && this.titleBar.headerStyle !== undefined) {
                  this.headerStyle = this.titleBar.headerStyle;
                }

                if (document.getElementById('superToolbar' + this.currentRootTabId)) {
                  setTimeout(() => {
                    try {
                      document.getElementById('superToolbar' + this.currentRootTabId).setAttribute("style", this.titleBar.cssStyle);
                    } catch (error) {

                    }
                  }, 5);
                }
                // // fixed andrew wen
                // if (this.titleBar && this.titleBar.back && this.titleBar.back.back) {
                //   localStorage.setItem("titleBarBackCount", this.titleBar.back.back);
                // }

                this.isGrayBg = pageData.isGrayBg;
                this.bgCssStyle = pageData.bgCssStyle;
                let ionScroll = await this.content.getScrollElement();
                ionScroll.style.background = this.bgCssStyle;
                this.isPageDisabled = pageData.disabled;
                this.showRefresher = pageData.showRefresher;
                this.showLoading = pageData.showLoading;
                this.backgroundImg = pageData.backgroundImg;
                this.showWaterImg = pageData.showWaterImg;
                this.showScrollToTopBtnTemp = pageData.scrollToTopBtn;
                if (this.footerComs && pageData.footerComs.length) {
                  localStorage.setItem("refreshFooterComsTag", JSON.stringify(pageData.footerComs[0].tagData));
                  // this.eventService.eventEmit.emit("refreshFooterComsContainer", "refreshFooterComsContainer");
                }
                this.getCurrentToggleData();
                this.sendShareIdToWx();

                
              });
            }
          } else {
            // 请求数据失败
            this.appGlobalService.showToast(res.message, 2000, 'middle');
          }
        }, err => {
          // 请求数据失败  add by jason he
          if (localStorage.getItem('netState') === 'No network connection') {
            this.netState = localStorage.getItem('netState');
          } else {
            this.netState = '';
          }
          this.showRefresh = true;
          this.titleBar = {
            background: 'white',
            back: { layout: 'left' },
            // errMessage: err.message ? err.message : null
          };

          if (err.code === '5502') {
            // 如果满足自动登录
            if(localStorage.getItem("ALP") && localStorage.getItem("loginAccount")){
              this.netState = 'showLoading';   
              this.showRefresh = false;
              this.http.delayShowLoading();
            } else {
              this.netState = '5502';   
            }
           
          }
        });
      }
    } catch (error) {
      console.log('error--->' + JSON.stringify(error));
    }
  }


  // 2024.10.10 
  refreshNav1FixedContainer() {
    setTimeout(() => {
      // 2024.10.10 首次进入APP有currentData则用currentData
      localStorage.setItem("dataMapFixedTabContainer", JSON.stringify(this.subTagData));
      this.eventService.eventEmit.emit('refreshNav1FixedContainer', 'refreshNav1FixedContainer');
    }, 200);
  }

  // 2023年9月25日新增
  processSwitchBlockTag() {
    if (Array.isArray(this.switchBlockTag)) {
      for (let j = 0; j < this.switchBlockTag.length; j++) {
        const element = this.switchBlockTag[j];
        if (j !== 0 && element.selected && element.selected === "true") {
          setTimeout(() => {
            const array = document.getElementsByClassName('switch-box-button-' + this.switchBlockTag.style);

            for (let k = 0; k < array.length; k++) {
              const subjectK = array[k] as HTMLElement;
              if (element.id === subjectK.id) {
                // subjectK.click();
                subjectK.click();
              }
            }
          }, 200);
        }
      }
    }

  }

  ngAfterViewInit(): void {
    setTimeout(() => {
      if (document.getElementById(this.subTagDataId) && this.subTagData && this.subTagData.data) {
        document.getElementById(this.subTagDataId).children[this.subTagData.currentTab].scrollIntoView({
          behavior: "smooth",
          inline: "center",
          block: "nearest",
        });
      }


    }, 650);


  }

  onTabsChange(i, item, currentData?) {
    this.isSpinning = true;
    this.tabPaneIndex = i.index;
    const mViewId = item[i.index].partLink.target;
    const mParams = item[i.index].partLink.params;
    this.http.post('application/part',
      {
        viewId: mViewId,
        sessionId: localStorage.getItem("sessionId"),
        params: mParams,
        tagOrder: 0
      }, (res: any) => {
        const tmpData = JSON.parse(res.script);
        this.subTagData.currentData.tags = tmpData.tags;
        this.currentDataArray[this.tabPaneIndex] = tmpData.tags;
        this.isSpinning = false;
      });
  }

  buttonClick(obj) {
    if (obj.type === 'page') {
      const params = {
        pageId: obj.target,
        params: {},
        sessionId: localStorage.getItem('sessionId')
      };
      if (obj.param) {
        params.params = { code: this.positionInfo.code };
      }
      this.appGlobalService.goToForward(params);
    } else if (obj.type === 'modal') {
      this.showCityModel(obj.target);
    }
  }

  async showCityModel(target) {
    const that = this;
    const modal = await this.modalController.create({
      component: ChooseCityComponent,
      componentProps: { value: target, type: 1, modalTitle: '选择地址' } // 首页是1 默认不传或者0
    });
    modal.onDidDismiss().then(() => {
      that.positionInfo = JSON.parse(localStorage.getItem('position'));
    });
    return await modal.present();
  }
  searchButtonClick(obj, ite?, e?) {

    // 2024.04.12 新增参数联调
    if (obj.link && obj.link.params
      && obj.link.params.key
      && obj.link.params.key.hasOwnProperty('latitude')
      && obj.link.params.key.hasOwnProperty('longitude')) {
      let position = JSON.parse(localStorage.getItem('position'));
      obj.link.params.key.latitude = position.center.lat;
      obj.link.params.key.longitude = position.center.lng;
      if (obj.link.params.key.useSelectedPosition !== undefined) {
        if (this.appGlobalService.searchShopLat !== undefined) {
          obj.link.params.key.latitude = this.appGlobalService.getAddressLat ? this.appGlobalService.getAddressLat : this.appGlobalService.searchShopLat;
        }
        if (this.appGlobalService.searchShopLng !== undefined) {
          obj.link.params.key.longitude = this.appGlobalService.getAddressLng ? this.appGlobalService.getAddressLng : this.appGlobalService.searchShopLng;
        }

      }
    }
    if (obj.searchType === '200') {

    }
    if (obj.searchType === '300') {
      if (e) {
        e.stopPropagation();
      }
      const searchPath = '/navSearch';

      this.router.navigate([searchPath], { queryParams: { obj: JSON.stringify(obj), ite } });
      return;
    }
    if (obj.partLink && obj.partLink.params && obj.partLink.params.key && obj.partLink.params.key.searchButtonCssStyle) {
      if (document.getElementsByTagName('app-nav-one')) {
        const navOneCollection = document.getElementsByTagName('app-nav-one') as HTMLCollection;
        for (let i = 0; i < navOneCollection.length; i++) {
          const el = navOneCollection[i];
          if (!this.hasClass(el, 'ion-page-hidden')) {
            const bottomSearch = el.getElementsByClassName('bottomSearchBox')[0] as HTMLElement;
            const searchDiv = bottomSearch.children[0] as HTMLElement;
            searchDiv.click();
            break;
          }
        }
      }
    } else {
      // search res back to search history
      if (obj.goTo && obj.goTo === "-1") {
        this.appGlobalService.popTarget();
        this.appGlobalService.goBack();
      } else {

        if (this.titleBar
          && this.titleBar.link
          && this.titleBar.link.link
          && this.titleBar.link.link.params
          && this.titleBar.link.link.params.useTitleBarLink !== undefined
        ) {
          this.pageModalService.openPage(this.titleBar.link.link);
        } else {
          // to history page
          console.log('to search history');
          localStorage.removeItem('searchParams');
          localStorage.removeItem('invitationArr');
          const searchPath = '/navSearch';
          this.router.navigate([searchPath], { queryParams: { obj: JSON.stringify(obj) } });
        }

      }
    }


  }
  getIndex(slides: IonSlides, data) {
    slides.getActiveIndex().then(index => {
      if (this.idx < data.length) {
        this.idx = index
      } else if (this.idx == data.length) {
        this.idx = index = 1;
      } else {
        this.idx = 0
      }

    })
  }
  slidesDidLoad(slides: IonSlides, data) {
    slides.startAutoplay();
    slides.getActiveIndex().then(index => {
      if (this.idx == data.placeholder.split('、').length) {
        this.idx = index = 1;
      }
    });
  }
  clickImg(data, e) {
    let ite = data.placeholder.split('、')
    this.searchButtonClick(data, ite[this.idx - 1], e)
  }

  /**
   * 关闭方法 登录后返回 刷新 返回再刷新一次上一个页面
   */
  close() {
    this.appGlobalService.goBack();
    this.appGlobalService.popTarget();
    // if (localStorage.getItem('needRefresh') !== 'true') {
    //   this.appGlobalService.popTarget();
    // }
  }
  /**
   * 返回方法
   */
  back() {
    this.appGlobalService.coms = [];
    if (this.coms && this.coms.length > 0) {
      this.appGlobalService.coms = this.coms
    }
    
    // 2.2.8 新增返回时关闭弹窗
    this.appGlobalService.closeAlertAndPopoverAndModalAndMenu();

    //2.2.16 H5 放回标记处理
    if (localStorage.getItem('detailPageFromH5') && localStorage.getItem('detailPageFromH5') === 'true') {
      localStorage.setItem('detailPageFromH5', 'false');
      // this.appGlobalService.popTarget();

      // back 支持配置返回层级数
      if (this.titleBar.back !== undefined && Number(this.titleBar.back.back) < 0) {
        const backNum = Number(this.titleBar.back.back);
        if (backNum === -999) {
          localStorage.setItem('needRefresh', 'true');
          if (document.getElementsByTagName('app-footer-coms') && document.getElementsByTagName('app-footer-coms').length > 0 && document.getElementsByTagName('app-footer-coms')[0].children[0].children[0].tagName === "APP-STORE-CONSULTANT") {
            localStorage.setItem('currAction', '0');
          } else {
            localStorage.removeItem('currAction');
          }
          this.appGlobalService.popTarget();
          this.appGlobalService.goBack();
        } else if (backNum === -998) {
          localStorage.removeItem('needRefresh');
          this.appGlobalService.popTarget();
          this.appGlobalService.goBack();
        } else {
          const back = Math.abs(Number(this.titleBar.back.back));
          for (let index = 0; index < back; index++) {
            this.appGlobalService.popTarget();
          }
          this.eventService.eventEmit.emit("loadFooterComponent", []);
          this.appGlobalService.goBack(Number(this.titleBar.back.back));
        }
      } else {
        // 没有配置 back 则 -2
        this.appGlobalService.popTarget();
        this.appGlobalService.popTarget();
        this.appGlobalService.goBack(-2);
      }
      return;
    }

    // 蜂喔商户2.2.6新增配置了disableBack这个属性会有值
    if (this.appGlobalService.showExit()) {
      return;
    }

    if (localStorage.getItem('back_target')) {
      localStorage.removeItem('back_target');
      // this.appGlobalService.popTarget();
      // this.appGlobalService.popTarget();
      // this.appGlobalService.goBack(-2);
      // return;
    }
    this.appGlobalService.openBackdrop = false;
    localStorage.removeItem('searchParams');
    localStorage.removeItem('invitationArr');
    // const that = this;

    // 1.9.0 改动需求新增参数
    if (localStorage.getItem('myrealEstateresetAssured')) {
      localStorage.removeItem('myrealEstateresetAssured');
    }

    if (localStorage.getItem('myrealEstatequickWay')) {
      localStorage.removeItem('myrealEstatequickWay');
    }

    if (localStorage.getItem('quote_way')) {
      localStorage.removeItem('quote_way');
    }


    // back 支持配置返回层级数
    if (this.titleBar.back !== undefined && Number(this.titleBar.back.back) < 0) {

      const backNum = Number(this.titleBar.back.back);
      if (backNum === -999) {
        localStorage.setItem('needRefresh', 'true');
        if (document.getElementsByTagName('app-footer-coms') && document.getElementsByTagName('app-footer-coms').length > 0 && document.getElementsByTagName('app-footer-coms')[0].children[0].children[0].tagName === "APP-STORE-CONSULTANT") {
          localStorage.setItem('currAction', '0');
        } else {
          localStorage.removeItem('currAction');
        }
        this.appGlobalService.popTarget();
        this.appGlobalService.goBack();
      } else if (backNum === -998) {
        localStorage.removeItem('needRefresh');
        this.appGlobalService.popTarget();
        this.appGlobalService.goBack();
      } else {
        const back = Math.abs(Number(this.titleBar.back.back));
        for (let index = 0; index < back; index++) {
          this.appGlobalService.popTarget();
        }
        this.eventService.eventEmit.emit("loadFooterComponent", []);
        this.appGlobalService.goBack(Number(this.titleBar.back.back));
      }


      if (this.titleBar.back && this.titleBar.back.refreshTab) {
        console.log(' go back and refreshTab', this.titleBar.back.refreshTab);
        setTimeout(() => {
          this.checkAndRefreshTabByIndex(this.titleBar.back.refreshTab);
        }, 500);
      }
    } else if (localStorage.getItem('fromPostOrEdit') === 'true') {
      // 铺铺旺发布后详情返回
      this.ppwPublishPageBack();
    } else {
      let cancelBackNow = false;
      if (this.coms && this.coms.length) {
        this.coms.forEach(element => {
          const style = element.tagData.style;
          if (cancelBackNow) {
            return;
          }
          switch (style) {
            // 当前是详情
            case 'tag.AppOppDetailTagLogic':
              if (!this.isPageDisabled && this.appGlobalService.tipsDiv && this.appGlobalService.tipsDiv !== undefined) {
                cancelBackNow = true;
                this.showTips();
              } else if (!this.isPageDisabled && this.appGlobalService.alertDiv && this.appGlobalService.alertDiv !== undefined) {
                cancelBackNow = true;
                this.showAlertDialog();
              }
              break;
            // 小旺发布
            case 'tag.AppGeneralFormTagLogic':
              cancelBackNow = true;
              if (this.appTypeCustom === 'LJ' || this.appTypeCustom === 'JS') {
                // 蜂喔APP发布点击返回 弹出提示文案按照需求文档修改
                cancelBackNow = true;
                let msg = "确定放弃本次发布？";
                let isBackRefresh = true;
                element.tagData.data.htmlObj.forEach(subHtmlObj => {
                  if (subHtmlObj && subHtmlObj.formType === 'backTips') {
                    msg = subHtmlObj.value;
                    if (subHtmlObj.showValue && subHtmlObj.showValue === 'onlyBack') {
                      // localStorage.setItem('needRefresh', 'false'); // 表单只是返回提示 不刷新前页面
                      isBackRefresh = false;
                      localStorage.removeItem('needRefresh');
                    } else if (subHtmlObj.showValue && subHtmlObj.showValue === 'onlyBackWithClickId') {
                      isBackRefresh = false;
                      localStorage.removeItem('needRefresh');
                      setTimeout(() => { localStorage.setItem('needRefresh', 'true'); }, 900);
                      $('#' + 'fixedNavTab1').click();
                    }
                  }
                });
                if (msg && msg !== '') {
                  this.sureCancel(msg, isBackRefresh);
                } else {
                  cancelBackNow = false;
                }
              } else {
                this.pxwPublishBack();
              }
              break;
            case 'tag.AppContract':
              cancelBackNow = true;
              this.sureCancel('确定放弃本次报价吗？');
              break;
            case 'tag.AppQuotedPriceTagLogic':
              cancelBackNow = true;
              this.sureCancel('确定放弃本次报价吗？');
              break;
            case 'appOnlinePriceTags':
              cancelBackNow = true;
              this.sureCancel('确定放弃操作？');
              break;
            case 'appDecorationPriceTags':
              cancelBackNow = true;
              this.sureCancel('确定放弃操作？');
              break;
            default:
              break;
          }
        });
        this.isPageDisabled = false;
        if (!cancelBackNow) {
          this.appGlobalService.popTarget();
          this.appGlobalService.goBack();
        }

      } else {
        this.appGlobalService.popTarget();
        // update by andrew.wen for fix bug
        // localStorage.setItem('clearFooterComsTag', 'clearFooterComsTag');
        // this.eventService.eventEmit.emit("clearFooterComs", []);
        // this.footerComs = [];
        // this.ref.markForCheck();
        // this.ref.detectChanges();
        this.appGlobalService.goBack();
      }
    }
    // debug 防止返回上级页面出现表单下一步UI
    this.appGlobalService.nextPageFomObj = undefined;

  }
  async sureCancel(msg, isBackRefresh?) {
    const alert = await this.alertController.create({
      header: '',
      subHeader: '',
      message: msg,
      buttons: [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: (blah) => {
          console.log('取消');
        }
      }, {
        text: '确定',
        cssClass: 'LJ',
        handler: () => {
          this.appGlobalService.globalParamNameObj = {};
          this.appGlobalService.goBack();
          this.appGlobalService.popTarget();
          if (isBackRefresh) {
            setTimeout(() => {
              this.checkAndRefreshTabByIndex(this.tabsService.tabPage);
            }, 500);
          } else {
            // 表单返回 撤销刷新标志
            localStorage.removeItem('needRefresh');
          }
        }
      }]
    });
    await alert.present();
  }

  // 2024.06.06 add by andrew for new params
  checkAndRefreshTabByIndex(tabsStr) {
    if (tabsStr.indexOf("tab") > -1) {
      const tab = tabsStr;
      const tabIndex = tab.substring(tab.length - 1);
      console.log("needRefreshTab" + tabIndex);
      localStorage.setItem('needRefreshTab' + tabIndex, 'true');
      this.eventService.eventEmit.emit(tabsStr, '1');
      console.log('submit back-eventEmit--->' + tabsStr);
    }
  }

  async pxwPublishBack() {
    // 铺小旺表单页面返回
    const alert = await this.alertController.create({

      header: '',
      subHeader: '',
      message: '确定返回吗？',
      buttons: [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: (blah) => {
          console.log('取消');
        }
      }, {
        text: '确定',
        cssClass: 'LJ',
        handler: () => {
          this.appGlobalService.globalParamNameObj = {};
          this.appGlobalService.goBack();
          this.appGlobalService.popTarget();
          // 表单返回 撤销刷新标志
          localStorage.removeItem('needRefresh');
          setTimeout(() => {
            if (this.tabsService.tabPage.indexOf("tab") > -1) {
              const tab = this.tabsService.tabPage;
              const tabIndex = tab.substring(tab.length - 1);
              console.log("needRefreshTab" + tabIndex);
              localStorage.setItem('needRefreshTab' + tabIndex, 'true');
              this.eventService.eventEmit.emit(this.tabsService.tabPage, '1');
              console.log('submit back-eventEmit--->' + this.tabsService.tabPage);
            }
          }, 500);
        }
      }]
    });
    await alert.present();

  }

  ppwPublishPageBack() {
    localStorage.removeItem('fromPostOrEdit');
    if (document.getElementById('fixedNavTab0')) {
      this.eventService.eventEmit.emit('refreshSubTab', 'refreshSubTab');
    } else {
      // 设置返回刷新前两级页面page级别
      localStorage.setItem('needRefresh-2', 'true');
    }

    this.appGlobalService.popTarget();
    this.appGlobalService.popTarget();
    this.appGlobalService.goBack(-2);

  }
  //
  //   "tipsDiv":{
  //     "plugin_id":"1",
  //     "downTag":Object{...},
  //     "numbers":"2,4,6,8",
  //     "title":"信息不好找?",
  //     "content":"立即联系找店顾问，为您整理推荐合适客户"
  // }


  showAlertDialog() {
    if (this.appGlobalService.alertDiv.plugin_id) {
      let count = '0';
      switch (this.appGlobalService.alertDiv.plugin_id) {
        case '1':
          count = this.appGlobalService.alertDivTotalCount.plugin_id1 + '';
          break;
        case '2':
          count = this.appGlobalService.alertDivTotalCount.plugin_id2 + '';
          break;
        case '3':
          count = this.appGlobalService.alertDivTotalCount.plugin_id3 + '';
          break;
        case '4':
          count = this.appGlobalService.alertDivTotalCount.plugin_id4 + '';
          break;
        case '5':
          count = this.appGlobalService.alertDivTotalCount.plugin_id5 + '';
          break;
        case '6':
          count = this.appGlobalService.alertDivTotalCount.plugin_id6 + '';
          break;
        case '7':
          count = this.appGlobalService.alertDivTotalCount.plugin_id7 + '';
          break;
        case '8':
          count = this.appGlobalService.alertDivTotalCount.plugin_id8 + '';
          break;
        case '9':
          count = this.appGlobalService.alertDivTotalCount.plugin_id9 + '';
          break;
        case '10':
          count = this.appGlobalService.alertDivTotalCount.plugin_id10 + '';
          break;
        case '11':
          count = this.appGlobalService.alertDivTotalCount.plugin_id11 + '';
          break;
        case '12':
          count = this.appGlobalService.alertDivTotalCount.plugin_id12 + '';
          break;
        case '13':
          count = this.appGlobalService.alertDivTotalCount.plugin_id13 + '';
          break;
        case '14':
          count = this.appGlobalService.alertDivTotalCount.plugin_id14 + '';
          break;
        case '15':
          count = this.appGlobalService.alertDivTotalCount.plugin_id15 + '';
          break;
        case '16':
          count = this.appGlobalService.alertDivTotalCount.plugin_id16 + '';
          break;
        case '17':
          count = this.appGlobalService.alertDivTotalCount.plugin_id17 + '';
          break;
        case '18':
          count = this.appGlobalService.alertDivTotalCount.plugin_id18 + '';
          break;
        case '19':
          count = this.appGlobalService.alertDivTotalCount.plugin_id19 + '';
          break;
        case '20':
          count = this.appGlobalService.alertDivTotalCount.plugin_id20 + '';
          break;
        case '21':
          count = this.appGlobalService.alertDivTotalCount.plugin_id21 + '';
          break;
        case '22':
          count = this.appGlobalService.alertDivTotalCount.plugin_id22 + '';
          break;
        case '23':
          count = this.appGlobalService.alertDivTotalCount.plugin_id23 + '';
          break;
        case '24':
          count = this.appGlobalService.alertDivTotalCount.plugin_id24 + '';
          break;
        case '25':
          count = this.appGlobalService.alertDivTotalCount.plugin_id25 + '';
          break;
        case '26':
          count = this.appGlobalService.alertDivTotalCount.plugin_id26 + '';
          break;
        case '27':
          count = this.appGlobalService.alertDivTotalCount.plugin_id27 + '';
          break;
        case '28':
          count = this.appGlobalService.alertDivTotalCount.plugin_id28 + '';
          break;
        case '29':
          count = this.appGlobalService.alertDivTotalCount.plugin_id29 + '';
          break;
        case '30':
          count = this.appGlobalService.alertDivTotalCount.plugin_id30 + '';
          break;
        case '31':
          count = this.appGlobalService.alertDivTotalCount.plugin_id31 + '';
          break;
        case '32':
          count = this.appGlobalService.alertDivTotalCount.plugin_id32 + '';
          break;
        case '33':
          count = this.appGlobalService.alertDivTotalCount.plugin_id33 + '';
          break;
        case '34':
          count = this.appGlobalService.alertDivTotalCount.plugin_id34 + '';
          break;
        case '35':
          count = this.appGlobalService.alertDivTotalCount.plugin_id35 + '';
          break;
        case '36':
          count = this.appGlobalService.alertDivTotalCount.plugin_id36 + '';
          break;
        case '37':
          count = this.appGlobalService.alertDivTotalCount.plugin_id37 + '';
          break;
        case '38':
          count = this.appGlobalService.alertDivTotalCount.plugin_id38 + '';
          break;
        case '100':
          count = this.appGlobalService.alertDivTotalCount.plugin_id100 + '';
          break;
        default:
          break;
      }
      const array = this.appGlobalService.alertDiv.numbers.split(',');
      if (array.indexOf(count) > -1) {
        // 匹配到对应的规则数
        this.presentAlertConfirm();

      } else {
        this.appGlobalService.popTarget();
        this.appGlobalService.goBack();
      }

    } else {
      this.appGlobalService.popTarget();
      this.appGlobalService.goBack();
    }
  }

  showTips() {
    if (this.appGlobalService.tipsDiv.plugin_id) {
      let count = '0';
      switch (this.appGlobalService.tipsDiv.plugin_id) {
        case '1':
          count = this.appGlobalService.tipsTotalCount.plugin_id1 + '';
          break;
        case '2':
          count = this.appGlobalService.tipsTotalCount.plugin_id2 + '';
          break;
        case '3':
          count = this.appGlobalService.tipsTotalCount.plugin_id3 + '';
          break;
        case '4':
          count = this.appGlobalService.tipsTotalCount.plugin_id4 + '';
          break;
        case '5':
          count = this.appGlobalService.tipsTotalCount.plugin_id5 + '';
          break;
        case '6':
          count = this.appGlobalService.tipsTotalCount.plugin_id6 + '';
          break;
        case '7':
          count = this.appGlobalService.tipsTotalCount.plugin_id7 + '';
          break;
        case '8':
          count = this.appGlobalService.tipsTotalCount.plugin_id8 + '';
          break;
        case '9':
          count = this.appGlobalService.tipsTotalCount.plugin_id9 + '';
          break;
        case '10':
          count = this.appGlobalService.tipsTotalCount.plugin_id10 + '';
          break;
        case '11':
          count = this.appGlobalService.tipsTotalCount.plugin_id11 + '';
          break;
        case '12':
          count = this.appGlobalService.tipsTotalCount.plugin_id12 + '';
          break;
        case '13':
          count = this.appGlobalService.tipsTotalCount.plugin_id13 + '';
          break;
        case '14':
          count = this.appGlobalService.tipsTotalCount.plugin_id14 + '';
          break;
        case '15':
          count = this.appGlobalService.tipsTotalCount.plugin_id15 + '';
          break;
        case '16':
          count = this.appGlobalService.tipsTotalCount.plugin_id16 + '';
          break;
        case '17':
          count = this.appGlobalService.tipsTotalCount.plugin_id17 + '';
          break;
        case '18':
          count = this.appGlobalService.tipsTotalCount.plugin_id18 + '';
          break;
        case '19':
          count = this.appGlobalService.tipsTotalCount.plugin_id19 + '';
          break;
        case '20':
          count = this.appGlobalService.tipsTotalCount.plugin_id20 + '';
          break;
        case '21':
          count = this.appGlobalService.tipsTotalCount.plugin_id21 + '';
          break;
        case '22':
          count = this.appGlobalService.tipsTotalCount.plugin_id22 + '';
          break;
        case '23':
          count = this.appGlobalService.tipsTotalCount.plugin_id23 + '';
          break;
        case '24':
          count = this.appGlobalService.tipsTotalCount.plugin_id24 + '';
          break;
        case '25':
          count = this.appGlobalService.tipsTotalCount.plugin_id25 + '';
          break;
        case '26':
          count = this.appGlobalService.tipsTotalCount.plugin_id26 + '';
          break;
        case '27':
          count = this.appGlobalService.tipsTotalCount.plugin_id27 + '';
          break;
        case '28':
          count = this.appGlobalService.tipsTotalCount.plugin_id28 + '';
          break;
        case '29':
          count = this.appGlobalService.tipsTotalCount.plugin_id29 + '';
          break;
        case '30':
          count = this.appGlobalService.tipsTotalCount.plugin_id30 + '';
          break;
        case '31':
          count = this.appGlobalService.tipsTotalCount.plugin_id31 + '';
          break;
        case '32':
          count = this.appGlobalService.tipsTotalCount.plugin_id32 + '';
          break;
        case '33':
          count = this.appGlobalService.tipsTotalCount.plugin_id33 + '';
          break;
        case '34':
          count = this.appGlobalService.tipsTotalCount.plugin_id34 + '';
          break;
        case '35':
          count = this.appGlobalService.tipsTotalCount.plugin_id35 + '';
          break;
        case '36':
          count = this.appGlobalService.tipsTotalCount.plugin_id36 + '';
          break;
        case '37':
          count = this.appGlobalService.tipsTotalCount.plugin_id37 + '';
          break;
        case '38':
          count = this.appGlobalService.tipsTotalCount.plugin_id38 + '';
          break;
        case '100':
          count = this.appGlobalService.tipsTotalCount.plugin_id100 + '';
          break;
        default:
          break;
      }
      const array = this.appGlobalService.tipsDiv.numbers.split(',');
      if (array.indexOf(count) > -1) {
        // 匹配到对应的规则数
        this.showRecommenTip();
      } else {
        this.appGlobalService.popTarget();
        this.appGlobalService.goBack();
      }

    } else {
      this.appGlobalService.popTarget();
      this.appGlobalService.goBack();
    }
  }

  async presentAlertConfirm() {
    try {
      this.isShowingAlertDiv = true;
      if (this.appTypeCustom === 'LJ') {
        const modal = await this.modalController.create({
          showBackdrop: true,
          cssClass: 'recommend-modal',
          animated: false,
          component: NewInquiryPageModalComponent,
          componentProps: { tagData: this.appGlobalService.alertDiv }
        });
        await modal.present();
        await modal.onDidDismiss().then((res) => {
          this.isShowingAlertDiv = false;
          this.appGlobalService.alertDiv = null;
          const targetObj = JSON.parse(localStorage.getItem('targetObj'));

          if (res.data && res.data.back) {
            this.appGlobalService.popTarget();
            this.appGlobalService.goBack();
          } else if (res.data && !res.data.back) {

          } else if (targetObj && targetObj.bat && targetObj.bat.length > 0) {
            this.appGlobalService.popTarget();
            this.appGlobalService.goBack();
          }
        });

      } else {
        const alert = await this.alertController.create({
          cssClass: 'my-custom-class',
          backdropDismiss: false,
          header: '',
          // tslint:disable-next-line:max-line-length
          message: '<span "height:2.75rem;font-size:1rem;font-weight:bold;color:rgba(39,40,46,1);">' + this.appGlobalService.alertDiv.title + '</span>',
          buttons: [
            {
              text: this.appGlobalService.alertDiv.cancel,
              role: 'cancel'
              ,
              handler: (blah) => {
                this.isShowingAlertDiv = false;
                this.appGlobalService.popTarget();
                this.appGlobalService.goBack();
              }
            }, {
              text:
                this.appGlobalService.alertDiv.button ?
                  this.appGlobalService.alertDiv.button.label :
                  this.appGlobalService.alertDiv.buttonLink[0].label,
              cssClass: 'custom-ok-btn',
              handler: () => {
                this.isShowingAlertDiv = false;
                // this.appGlobalService.isShowInquiryPageModal = true;
                if (this.appGlobalService.alertDiv.button && this.appGlobalService.alertDiv.button.submit !== undefined) {
                  const params = {
                    content: this.appGlobalService.alertDiv.button.submit.content,
                    id: this.appGlobalService.alertDiv.button.submit.id,
                    sessionId: localStorage.getItem('sessionId')
                  };
                  this.http.post('application/submit', params, res => {
                    // 请求数据成功
                    if (res.success === true) {
                      this.appGlobalService.showToast(res.message, 2000, 'middle');
                      this.appGlobalService.reloadCurrentPage();
                    } else {
                      // 请求数据失败
                      this.appGlobalService.showToast(res.message, 2000, 'middle');
                    }
                  });
                } else if (this.appGlobalService.alertDiv.buttonLink && this.appGlobalService.alertDiv.buttonLink[0].submit !== undefined) {
                  const params = {
                    content: this.appGlobalService.alertDiv.buttonLink[0].submit.content,
                    id: this.appGlobalService.alertDiv.buttonLink[0].submit.id,
                    sessionId: localStorage.getItem('sessionId')
                  };
                  this.http.post('application/submit', params, res => {
                    // 请求数据成功
                    if (res.success === true) {
                      this.appGlobalService.showToast(res.message, 2000, 'middle');
                      setTimeout(() => {
                        this.eventService.eventEmit.emit('reloadCurrentPage', '1');
                        // localStorage.setItem('needRefresh', 'true');// jason 7.31 移除 解除刷新之前的页面
                      }, 2000);
                    } else {
                      // 请求数据失败
                      this.appGlobalService.showToast(res.message, 2000, 'middle');
                    }
                  });
                }
                if (!localStorage.getItem('userInfo')
                  && this.appGlobalService.alertDiv.button
                  && this.appGlobalService.alertDiv.button.link) {

                  this.appGlobalService.openPage(this.appGlobalService.alertDiv.button.link);

                } else if (!localStorage.getItem('userInfo')
                  && this.appGlobalService.alertDiv.buttonLink[0]
                  && this.appGlobalService.alertDiv.buttonLink[0].link) {
                  const pageParams = {
                    pageId: this.appGlobalService.alertDiv.buttonLink[0].link.target,
                    params: this.appGlobalService.alertDiv.buttonLink[0].link.params,
                    sessionId: localStorage.getItem('sessionId')
                  };
                  this.appGlobalService.openPage(this.appGlobalService.alertDiv.buttonLink[0].link);
                }
              }
            }
          ]
        });
        await alert.present();
      }
    } catch (error) {
      console.log('error------>' + JSON.stringify(error));
    }
  }
  async presentAlertWithMsgBtn(msg, btnText, button) {
    const alert = await this.alertController.create({
      message: msg,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: btnText,
          handler: () => {
            // this.httpService.changeCallNumber(mobile);
            const params = {
              content: button.submit.content,
              id: button.submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.http.post("application/submit", params, res => {
              if (res.success) {
                this.appGlobalService.showToast(res.message, 1500, "middle");
                setTimeout(() => {
                  this.eventService.eventEmit.emit('reloadCurrentPage', '1');
                }, 1500);
              }
            });
          }
        }
      ]
    });
    await alert.present();
  }

  async showRecommenTip() {
    this.isShowingTipsDiv = true;
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'recommend-modal',
      component: RecommendModalComponent,
      componentProps: { tipData: this.appGlobalService.tipsDiv },
      enterAnimation: ModalFromCenterEnter,
      leaveAnimation: ModalFromCenterLeave,

    });
    await modal.present();
    // 监听销毁的事件
    await modal.onDidDismiss().then((res) => {
      this.isShowingTipsDiv = false;
      this.appGlobalService.tipsDiv = null;
      if (res.data === undefined && res.role === undefined) {
        this.appGlobalService.popTarget();
        this.appGlobalService.goBack();
        // tslint:disable-next-line:no-string-literal
      } else if (res && res.data && res.data['isBack'] !== true) { // 点击modal之外的取消区域
      }
    }); // 获取关闭传回的值
  }
  /** 收藏 */
  favorite(submit) {
    // 判断是否登录 登录 返回 详情
    const params = {
      id: submit.id,
      content: submit.content,
      sessionId: localStorage.getItem('sessionId')
    };

    console.log('favorite --> submit', params);
    this.http.post('application/submit', params, res => {
      // 请求成功
      if (res.success) {
        // 更新收藏icon UI
        if (this.titleBar.favorite.icon === "unfavorite") {
          this.titleBar.favorite.icon = "favorite";
        } else {
          this.titleBar.favorite.icon = "unfavorite";
        }
        console.log('favorite -->', res.message);
      } else {
        // 请求数据失败
        // this.appGlobalService.showToast(res.message, 2000, 'middle');
        if (res.type === 'page') {
          // const loginParams = {
          //   pageId: res.target,
          //   params: res.params ? res.params : {},
          //   sessionId: localStorage.getItem('sessionId')
          // };
          // to login

          this.pageModalService.openPage({ type: 'page', target: res.target, params: res.params ? res.params : {} })
        }
      }
    });
  }

  /** 拨打客服 */

  async call(data) {
    console.log(' 拨打客服 ', data);
    const message = data.name ? data.name + ' ' + data.phone : data.phone;
    const alert = await this.alertController.create({

      header: '',
      subHeader: '',
      message: data.title + '<br>' + message,
      buttons: [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: (blah) => {
          console.log('取消');
        }
      }, {
        text: '拨打',
        cssClass: 'LJ',
        handler: () => {
          this.http.changeCallNumber(data.phone);
        }
      }]
    });
    await alert.present();
  }

  // 分享弹框
  async presentModal(title) {
    const modal = await this.modalController.create({
      showBackdrop: true,
      cssClass: 'sharePage',
      backdropDismiss: true,
      component: SharePageComponent,
      componentProps: { tagData: this.shareData, title: title === null ? "" : title }
    });
    await modal.present();
    // 监听销毁的事件
    const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
    console.log(modalData);
  }

  /** 分享 */
  share(link) {
    if (link && link.params
      && link.params.doNotRequestPageBeforeJumpToSharePage !== undefined
      && link.params.doNotRequestPageBeforeJumpToSharePage === 'true') {
      this.pageModalService.openPage(link);
    } else {
      // 请求参数
      const params = {
        sessionId: localStorage.getItem("sessionId"),
        pageId: link.target,
        params: link.params
      };
      this.http.post('application/page', params, res => {
        const tagData = JSON.parse(res.script).views[0].tags[0];
        // 2024.07.10 兼容以前的标签
        if (tagData.style !== 'shareDetailTag') {
          this.pageModalService.openPage(link);
        } else {
          this.shareData = tagData.data;
          this.presentModal(tagData.title);
        }
      });
    }
  }

  change(obj, indexTab) {
    if (obj !== undefined && obj.partLink !== undefined) {
      this.tagData.currentTab = indexTab;

      if (localStorage.getItem('topTapPart' + indexTab)) {
        const parseData = JSON.parse(localStorage.getItem('topTapPart' + indexTab));
        this.tagData.currentData = parseData;
        setTimeout(() => {
          localStorage.setItem("dataMapTopTabContainer", JSON.stringify(this.tagData));
          this.eventService.eventEmit.emit('refreshTopTabContainer', 'refreshTopTabContainer');
          this.content.scrollToTop(0);
        }, 200);
      } else {
        this.http.post('application/part',
          {
            viewId: obj.partLink.target,
            sessionId: localStorage.getItem("sessionId"),
            params: obj.partLink.params
          }, (res: any) => {
            // #616 修改：点击转让服务和选址服务跳到第一屏的画面
            this.content.scrollToTop(0);
            if (res !== undefined && res != null) {
              setTimeout(() => {
                this.tagData.currentData = JSON.parse(res.script);
                localStorage.setItem("dataMapTopTabContainer", JSON.stringify(this.tagData));
                this.eventService.eventEmit.emit('refreshTopTabContainer', 'refreshTopTabContainer');
              }, 50);

            }
          });
      }
    }
  }

  subChange(obj, indexTab, className?) {
    this.eventService.removeCustomListListeners();
    if (obj !== undefined && obj.partLink !== undefined) {
      this.subTagData.currentTab = indexTab;
      localStorage.setItem('navCurrTabIndx', indexTab);
      const assignParams = obj.partLink.params;
      if (localStorage.getItem('myrealEstateOppId')) {
        const oppId = localStorage.getItem('myrealEstateOppId');
        assignParams.opportunity_id = oppId;
        localStorage.removeItem('myrealEstateOppId');
      }
      if (this.appTypeCustom === 'LJ') {
        if (assignParams.quote_way) {
          localStorage.setItem('quote_way', assignParams.quote_way);
        }
      }
      localStorage.setItem('assignParams', JSON.stringify(assignParams));

      // 不显示‘全部’分类下的 二级分类
      if ((className === 'newCss' || className === 'newCss2') && Number(indexTab) === 0 && obj.label && obj.label === '全部') {
        this.showSwitchBlockTag = false;
        $('.switch-main-box-newCss').show();
        $('.switch-main-box-newCss-bottom').hide(100);
        this.appGlobalService.openBackdrop = false;
      } else {
        this.showSwitchBlockTag = true;
      }
      // if (this.switchBtnParamFilter) {
      //   Object.assign(assignParams, this.switchBtnParamFilter);
      // }


      // 2023.11.28 通过link_type判断是否要跳转页面

      if (obj.partLink.params && obj.partLink.params.link_type && obj.partLink.params.link_type === 'page') {
        let link =
        {
          params: obj.partLink.params,
          target: obj.partLink.params.link_target,
          type: obj.partLink.params.link_type
        };
        this.pageModalService.openPage(link);
      } else {
        if (this.currentFixedTagArray[indexTab] && this.appGlobalService.needCheckTabName === undefined) {
          const convertObj = JSON.parse(JSON.stringify(this.currentFixedTagArray[indexTab]));
          if (convertObj.currentData.tags[0].name === 'switchBlockTag') {
            this.switchBlockTag = convertObj.currentData.tags[0];
            console.log('this.switchBlockTag 9');
            if (this.switchBlockTag) {
              if (this.switchBlockTag.style === 'newCss2') {
                this.switchBlockTagClassNameType = 1;
              }
              this.processSwitchBlockTag();
            }
          } else {
            this.switchBlockTag = null;
          }

          const len = convertObj.currentData.tags.length - 1;
          this.isRefreshAfterCLickSwitchButton =
            (convertObj.currentData.tags[len]
              && convertObj.currentData.tags[len].id !== undefined);
          if (convertObj.currentData.tags[len]
            && convertObj.currentData.tags[len].id !== undefined) {
            this.refreshFilterId = convertObj.currentData.tags[len].id;
          }

          localStorage.setItem('refreshGrayBgTag', '' + convertObj.currentData.isGrayBg);
          this.eventService.eventEmit.emit('refreshGrayBg', 'refreshGrayBg');
          localStorage.setItem("dataMapFixedTabContainer", JSON.stringify(convertObj));
          this.eventService.eventEmit.emit('refreshNav1FixedContainer', 'refreshNav1FixedContainer');
        } else {
          if (this.appGlobalService.needCheckTabName !== undefined
            && this.appGlobalService.needCheckTabName !== '') {
            if (this.appGlobalService[this.appGlobalService.needCheckTabName]
              && assignParams[this.appGlobalService.needCheckTabName] !== undefined) {
              assignParams[this.appGlobalService.needCheckTabName] = this.appGlobalService[this.appGlobalService.needCheckTabName];
            }
          }
          this.pageModalService.jsongetPostData(this.http.bathUrl+'application/part',
            {
              viewId: obj.partLink.target,
              sessionId: localStorage.getItem("sessionId"),
              params: assignParams
            }, (res: any) => {
              if (res !== undefined && res != null) {
                setTimeout(() => {
                  this.subTagData.currentData = JSON.parse(res.script);
                  // 如果我的物业tab包含筛选新标签则赋值新筛选tag
                  if (this.subTagData.currentData.tags[0].name === 'switchBlockTag') {
                    this.switchBlockTag = this.subTagData.currentData.tags[0];
                    console.log('this.switchBlockTag 15');
                    if (this.switchBlockTag) {
                      if (this.switchBlockTag.style === 'newCss2') {
                        this.switchBlockTagClassNameType = 1;
                      } else if (this.switchBlockTag.style === 'newCss3') {
                        this.switchBlockTagClassNameType = 1;
                      }
                      this.processSwitchBlockTag();
                    }
                  } else {
                    this.switchBlockTag = null;
                  }

                  const len = this.subTagData.currentData.tags.length - 1;
                  this.isRefreshAfterCLickSwitchButton =
                    (this.subTagData.currentData.tags[len]
                      && this.subTagData.currentData.tags[len].id !== undefined);
                  if (this.subTagData.currentData.tags[len]
                    && this.subTagData.currentData.tags[len].id !== undefined) {
                    this.refreshFilterId = this.subTagData.currentData.tags[len].id;
                  }
                  localStorage.setItem('refreshGrayBgTag', '' + this.subTagData.currentData.isGrayBg);
                  this.eventService.eventEmit.emit('refreshGrayBg', 'refreshGrayBg');
                  localStorage.setItem("dataMapFixedTabContainer", JSON.stringify(this.subTagData));
                  this.eventService.eventEmit.emit('refreshNav1FixedContainer', 'refreshNav1FixedContainer');

                }, 50);

                setTimeout(() => {
                  const tempConvertObj = JSON.parse(JSON.stringify(this.subTagData));
                  if (!this.currentFixedTagArray[indexTab]) {
                    console.log('createCurrentFixedTagArray=', new Date().toLocaleDateString());
                    this.currentFixedTagArray[indexTab] = tempConvertObj;
                  }
                }, 200);

              }
            });
        }

      }





    }
  }
  // 聊天
  chat(chat) {
    if (chat.link && chat.link.type === 'chat') {
      const cityId = JSON.parse(localStorage.getItem('position')) ? JSON.parse(localStorage.getItem('position')).code : 4403;
      const ifLogin = localStorage.getItem('userId') !== 'null';
      if (ifLogin) {
        if (chat.link.params.opportunity_id) {
          this.http.getImId(chat.link.params.opportunity_id,
            chat.link.params.customer_id, cityId, (item) => {
              if (item.toId !== localStorage.getItem('userId')) {
                // tslint:disable-next-line:max-line-length
                this.chatService.enterTheChatRoomUseUserId = item.toId;
                if (this.chatService.enterTheChatRoomUseUserId !== '') {
                  localStorage.setItem('enterChatRoomByUserId', '1');
                  this.eventService.eventEmit.emit('enterChatRoomByUserId',
                    { userId: this.chatService.enterTheChatRoomUseUserId, fromFriendList: true });
                }
              }
            });
        } else {
          try {
            this.chatService.enterTheChatRoomUseUserId = chat.link.params.customer_id;
            if (this.chatService.enterTheChatRoomUseUserId !== '') {
              localStorage.setItem('enterChatRoomByUserId', '1');
              this.eventService.eventEmit.emit('enterChatRoomByUserId',
                { userId: this.chatService.enterTheChatRoomUseUserId, fromFriendList: true });
            }
          } catch (error) {
            console.log('error----->' + JSON.stringify(error));
          }
        }
      }
    }
  }
  // 更多
  moreLine(more) {
    const that = this;
    const buttons: any = [];

    more.data.forEach((element, index) => {
      buttons.push(element.label);
    });

    if (more.style !== undefined) {
      // todo 有style的时候显示popover
      this.presentPopover(null, more.data);
    } else {
      // todo 动作菜单
      ActionSheetService.showActionSheetWithOptions(
        {
          options: buttons,
          maskClosable: true
        },
        buttonIndex => {
          if (buttonIndex > -1) {
            console.log(more.data[buttonIndex]);
            ActionSheetService.close();
            setTimeout(() => {
              that.selectItem(more.data[buttonIndex]);
            }, 200);
          }
        }
      );
    }



  }
  selectItem(item) {
    if (item.action === 'submit') {

      item.submit.sessionId = localStorage.getItem('sessionId');
      console.log('more --> submit', item.submit);
      this.http.post('application/submit', item.submit, res => {
        this.appGlobalService.showToast(res.message, 2000, 'middle');
        if (res && res.params && res.params.back === '0') {
          this.appGlobalService.reloadCurrentPage();
        } else if (item.submit.content.back === '-1.0' && res.success) {
          this.appGlobalService.popTarget();
          this.appGlobalService.goBack();
        }

      });

    } else if (item.action === 'filter') {
      // 实现服务大厅页面，拥有“分公司服务大厅”权限与加盟店服务大厅”权限时，可见右上角的筛选分公司/加盟店数据的按钮，点击后可以筛选数据，默认“分公司”
      // 如果titleBar中的moreLine返回filterSubmit，那么就直接调取切换标签下面的列表id，然后把数据传入到content，请求submit后刷新页面，记得把切换标签的条件全部重置。
      console.log('more --> filterSubmit ', item.filterSubmit);
      // 选中结果
      const result: any = {
        // showName: "",
        filter: item.filterSubmit.content,
        order: {}
      };
      this.message.clearMessage();
      this.message.sendMessage(result);

    } else if (item.action === 'link') {
      this.pageModalService.openPage(item.link);
    } else if (item.action === 'question') {
      // alert
      this.question(item);
    } else if (item.action === 'prompt') {
      // 弹出输入框 alert
      this.inputAlert(item);
    } else if (item.action === 'modal') {
      this.openRankingModal("ranking-modal", item);
    } else if (item.action === 'refresh') {
      this.refreshPage();
    } else if (item.action === 'view') {
      const param = {
        viewId: item.link.target,
        params: item.link.params ? item.link.params : {},
        sessionId: localStorage.getItem('sessionId')
      };
      this.appGlobalService.goToForward(param);
    } else if (item.action === "share") {
      this.share(item.link);
    } else if (item.action === "resetPassword") {
      this.resetPassword(item);
    } else if (item.action === "enableAccount") {
      this.presentAlertWithMsgBtn(item.text ? item.text : "确定启用该账号", item.label, item);
    } else if (item.action === "back" || item.action === "backNoRefresh") {
      if (item.action === "backNoRefresh") {
        localStorage.removeItem('needRefresh');
      }
      this.appGlobalService.popTarget();
      this.appGlobalService.goBack();
    }
  }

  resetPassword(item) {
    const params = {
      sessionId: localStorage.getItem("sessionId"),
      pageId: item.link.target,
      params: item.link.params
    };
    this.http.post('application/page', params, async res => {

      const modal = await this.modalController.create({
        showBackdrop: true,
        cssClass: 'resetPassword',
        component: NestedFormTagComponent,
        componentProps: { pageData: res, cssClass: 'resetPassword' }
      });
      await modal.present();
      const modalData = await modal.onDidDismiss();
    });
  }


  // ranking-modal
  async openRankingModal(className, item) {
    const params = {
      sessionId: localStorage.getItem("sessionId"),
      pageId: item.link.target,
      params: item.link.params
    };
    this.http.post('application/page', params, async res => {
      const tagData = JSON.parse(res.script).views[0].tags[0].data;
      const style = JSON.parse(res.script).views[0].tags[0].style;

      if (style === 'appPopupTag') { // modalOfShowPhoneTag
        // 是否公开号码
        const modal = await this.modalController.create({
          showBackdrop: true,
          cssClass: 'show-phone-modal',
          component: ShowPhoneModalComponent,
          componentProps: { tagData }
        });
        await modal.present();
        // 监听销毁的事件
        const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
      } else {
        // "ranking-modal"
        const modal = await this.modalController.create({
          showBackdrop: true,
          cssClass: className,
          component: RankingModalComponent,
          componentProps: { tagData }
        });
        await modal.present();
        // 监听销毁的事件
        const modalData = await modal.onDidDismiss(); // 获取关闭传回的值
      }
    });
  }
  // alert
  async question(item, keys?) {
    const that = this;
    const alert = await this.alertController.create({

      header: '',
      subHeader: '',
      message: item.question,
      buttons: [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: (blah) => {
          console.log('取消');
        }
      }, {
        text: '确定',
        cssClass: 'LJ',
        handler: () => {

          if (item.paramName && item.paramName.indexOf('isJsonArray')) {
            const keyString: string = item.paramName;
            keys = keyString.split(',');
            let count = 0;
            let formCount = 0;
            keys.forEach(element => {
              const formGroup: FormGroup = this.appGlobalService.getFormGroupWithParamName(element);
              const messageObj = this.appGlobalService.getFormGroupMessageWithParamName(element);
              const compareArray = this.appGlobalService.getFormCompareWithParamName(element);
              if (formGroup && messageObj) {
                formCount += 1;
                this.appGlobalService.formChecked = true;
                this.valid(formGroup, messageObj, compareArray, params => {
                  if (params) {
                    item.submit.content[element] = params;
                    count += 1;
                  } else {
                    return;
                  }
                });
              }
            });
            // 全部校验通过
            if (count === formCount) {
              if (item.alterMessage && item.alterMessage.length > 0) {
                this.postFormDataTip(item);
              } else {
                this.postFormData(item);
              }
            }
          } else {
            item.submit.sessionId = localStorage.getItem('sessionId');
            console.log('more --> submit', item.submit);
            this.http.post('application/submit', item.submit, res => {
              // 刷新当前页面
              if (item.submit.content.back && item.submit.content.back === '0') {
                this.http.reloadCurrentPage();
                setTimeout(() => {
                  // localStorage.setItem('needRefresh', 'true'); // jason 7.31 移除 解除刷新之前的页面
                  this.appGlobalService.showToast(res.message, 2000, 'middle');
                }, 1000);
              } else {
                this.appGlobalService.showToast(res.message, 2000, 'middle');
              }
            });
          }


        }
      }]
    });
    await alert.present();

  }

  inputAlert(item) {
    const that = this;
    ModalService.prompt(
      item.htmlObj.title,
      '',
      [
        // {
        //   text: 'Close',
        //   onPress: value =>
        //     new Promise(resolve => {
        //       setTimeout(() => {
        //         resolve();
        //         console.log(`value:${value}`);
        //       }, 1000);
        //     })
        // },
        {
          text: item.htmlObj.buttonLabel,
          onPress: value =>
            new Promise<void>((resolve) => {
              if (value.length === 0 || that.appGlobalService.isPhone(value)) {
                resolve();
                item.submit.content[item.htmlObj.input.formKey] = value;
                item.submit.sessionId = localStorage.getItem('sessionId');
                console.log('more --> submit', item.submit);
                that.http.post('application/submit', item.submit, res => {
                  if (res.message) {
                    this.appGlobalService.showToast(res.message, 2000, 'middle');
                  }
                });
              } else {
                that.appGlobalService.showToast('请输入正确的号码', 2000, 'top');
              }
            })
        }
      ],
      'default',
      null,
      [item.htmlObj.input.placeholder]
    );
  }
  //
  filter(filter) {
    const param = {
      pageId: filter.link.target,
      params: filter.link.params ? filter.link.params : {},
      sessionId: localStorage.getItem('sessionId')
    };
    this.appGlobalService.goToForward(param);
  }

  // 确定提交表单用
  textButton(textButton, searchInput?) {
    if (searchInput) {
      // console.log(textButton);
      if (textButton && textButton.link.params.eventName) {
        const listenerName = textButton.link.params.eventName + 'AskForList';
        Object.keys(searchInput.link.params).forEach(key => {
          searchInput.link.params[key] = this.keyword;
        });
        this.eventService.eventEmit.emit(listenerName, searchInput.link);
      }
    } else {
      this.check(textButton);
    }
  }
  // 数组btn
  iconButtonClick(item) {
    this.selectItem(item);
  }

  toggle(toggleButton, index) {
    this.appGlobalService.openBackdrop = false; //2.2.19 筛选已经打开修复从生活订单切换到其他订单，筛选DIV没有隐藏
    if (toggleButton[index].checked) {
      return;
    }
    toggleButton.forEach((element, i) => {
      if (i === index) {
        // 2.2.19 fixed bug 选中了才调用part接口
        this.toggleChange(toggleButton[index], index);
        element.checked = true;

      } else {
        element.checked = false;
      }
      if (toggleButton[index].partLink && toggleButton[index].partLink.params && toggleButton[index].partLink.params.hiddeRightBtn) {
        this.titleBar.showRightBtn = toggleButton[index].partLink.params.hiddeRightBtn;
      } else {
        this.titleBar.showRightBtn = false;
      }

    });

  }

  getCurrentToggleData() {
    if (this.titleBar && this.titleBar.toggleButton) {
      this.titleBar.toggleButton.forEach((e, i) => {
        if (e.checked) {
          this.toggleChange(e, i.toString());
          if (e.partLink && e.partLink.params && e.partLink.params.hiddeRightBtn) {
            this.titleBar.showRightBtn = e.partLink.params.hiddeRightBtn;
          } else {
            this.titleBar.showRightBtn = false;
          }
        }
      });
    }
  }

  toggleChange(obj, index?) {

    if (obj !== undefined && obj.partLink !== undefined) {
      this.http.post('application/part',
        {
          viewId: obj.partLink.target,
          sessionId: localStorage.getItem("sessionId"),
          params: obj.partLink.params
        }, (res: any) => {
          if (res !== undefined && res != null) {
            this.tabsService.getPageData(res, pageData => {
              this.coms = pageData.coms;
              if (this.coms[0] && this.coms[0].tagData.style === 'tag.AppTabTagLogic' && this.coms[0].tagData.name === 'imagesTag') {
                this.subComs = this.coms;
                this.coms = undefined;
                this.showSubTab = true;
                this.showTopTab = false;
                this.subTagData = this.subComs[0].tagData;
                this.selectedSegment = +this.subTagData.currentTab;
                this.currentDataArray = new Array(this.subTagData.data.length);
                this.currentDataArray[this.tabPaneIndex] = this.subTagData.currentData.tags;
                this.tabBarUnderlineStyle = { border: '1px solid #ffca3a', bottom: '4px', background: '#0A3CA0', width: '2rem' };
                this.tabBarUnderlineStyle['margin-left'] = 'calc(( 100vw / ' + this.subTagData.data.length + '  - 2.5rem) * 0.5)';
                this.subAWidth = 100 / this.subTagData.data.length + '%';
                // 如果我的物业tab包含筛选新标签则赋值新筛选tag
                if (this.subComs[0] && this.subComs[0].tagData.currentData.tags[0].name === 'switchBlockTag') {
                  this.switchBlockTag = this.subComs[0].tagData.currentData.tags.shift();
                  console.log('this.switchBlockTag 24')
                  if (this.switchBlockTag) {
                    if (this.switchBlockTag.style === 'newCss2') {
                      this.switchBlockTagClassNameType = 1;
                    }
                    this.processSwitchBlockTag();
                  }
                }
                const len = this.subComs[0].tagData.currentData.tags.length - 1;
                if (!isNaN(len)
                  && this.subComs[0]
                  && this.subComs[0].tagData.currentData.tags[len].style === "tag.AppGeneralButtonTagLogic") {
                  this.isRefreshAfterCLickSwitchButton =
                    (this.subComs[0].tagData.currentData.tags[len]
                      && this.subComs[0].tagData.currentData.tags[len].id !== undefined);
                  if (this.subComs[0].tagData.currentData.tags[len]
                    && this.subComs[0].tagData.currentData.tags[len].id !== undefined) {
                    this.refreshFilterId = this.subComs[0].tagData.currentData.tags[len].id;
                  }
                }
                // add by andrew.wen for newCss2 switchBlockTag
                this.showSwitchBlockTag = true;
              } else {
                this.showSwitchBlockTag = false;
                if (this.subComs !== undefined) {
                  this.subComs = undefined;
                }
              }

              this.headerComs = pageData.headerComs; // 2024.03.21 tab选项卡支持 linearLayout="header" 配置
              this.footerComs = pageData.footerComs;
              if (pageData.titleBar !== undefined) {
                // 1.9.0 改动  5 新增
                // 新增搜索输入框 与 购物车按钮 
                if (pageData.titleBar.searchInput !== undefined) {
                  this.titleBar['searchInput'] = pageData.titleBar.searchInput;
                }
                // 购物车按钮
                if (pageData.titleBar.cart !== undefined) {
                  this.titleBar['cart'] = pageData.titleBar.cart;
                }
                // 样式
                if (pageData.titleBar.cssStyle !== undefined) {
                  this.titleBar['cssStyle'] = pageData.titleBar.cssStyle;
                }
                // 底部border线
                if (pageData.titleBar.bottomLine !== undefined) {
                  this.titleBar['bottomLine'] = pageData.titleBar.bottomLine;
                }
              }
            });
          }
        });
    }
  }

  // tslint:disable-next-line:ban-types
  valid(formGroup: FormGroup, allLabel, compareArray, callback: Function) {
    if (formGroup.valid) {
      // console.log(this.formGroup.value);
      const params = formGroup.value;
      // tslint:disable-next-line:forin
      for (const prop in params) {
        if (Array.isArray(params[prop])) {
          params[prop] = params[prop].join(',');
        }
        // 删除无效值
        if (prop === '') {
          // delete params[prop];
        }
        if (prop.indexOf('samekey_') > -1) {
          const p = prop.replace('samekey_', '');
          params[p] = params[prop] ? params[prop] : "";
          delete params[prop];
        }
      }
      let compare = true;

      for (let index = 0; index < compareArray.length; index++) {
        const compareItem = compareArray[index];
        if (Number(params[compareItem.minKey]) > Number(params[compareItem.maxKey])) {
          console.log(params[compareItem.minKey]);
          console.log(params[compareItem.maxKey]);
          if (compareItem.lessTip && compareItem.lessTip.length > 0) {
            this.appGlobalService.showToast(compareItem.lessTip, 3000, 'top');
          } else {
            this.appGlobalService.showToast(`最小${compareItem.label}不得大于/等于最大${compareItem.label}`, 3000, 'top');
          }

          compare = false;
          break;
        } else if (Number(params[compareItem.minKey]) === Number(params[compareItem.maxKey]) && Number(params[compareItem.minKey]) != 0) {
          console.log(params[compareItem.minKey]);
          console.log(params[compareItem.maxKey]);
          if (compareItem.canEqual) {
            continue
          } else if (compareItem.equalTip && compareItem.equalTip.length > 0) {
            this.appGlobalService.showToast(compareItem.equalTip, 3000, 'top');
          } else {
            this.appGlobalService.showToast(`最小${compareItem.label}不得大于/等于最大${compareItem.label}`, 3000, 'top');
          }

          compare = false;
          break;
        }
      }
      if (compare) {
        console.log(params);
        callback(params);
      }
      // this.onReset();
    } else {
      this.getErrors(formGroup, allLabel);
    }
  }

  getErrors(form, allLabel) {
    const errs = [];
    for (const name in form.controls) {
      // eg: controls[name] = phone
      if (form.controls[name].errors) {
        errs.push({ key: [name], err: form.controls[name].errors });
      }
    }
    if (errs.length) {
      const errItem = errs[0];

      const firstErrMsgKey = Object.keys(errItem.err)[0];
      console.log(errItem.key, '校验的字段名');
      const messageObj = allLabel[errItem.key];
      const showMessage = messageObj[firstErrMsgKey];
      this.appGlobalService.showToast(showMessage, 3000, 'top');

    }
  }



  check(item) {
    console.log(item.action);
    const keyString: string = item.paramName;
    let keys = keyString ? keyString.split(',') : [];
    // if (!keys) {
    //   return;
    // }
    if (item.action === 'reset') {

      keys.forEach(element => {
        const formGroup: FormGroup = this.appGlobalService.getFormGroupWithParamName(element);

        if (formGroup) {
          formGroup.reset();
        }
      });

    } else if (item.action === 'submit') {


      const keyString: string = item.paramName;
      keys = keyString.split(',');
      let count = 0;
      let formCount = 0;
      keys.forEach(element => {
        const formGroup: FormGroup = this.appGlobalService.getFormGroupWithParamName(element);
        const messageObj = this.appGlobalService.getFormGroupMessageWithParamName(element);
        const compareArray = this.appGlobalService.getFormCompareWithParamName(element);
        if (formGroup && messageObj) {
          formCount += 1;
          this.valid(formGroup, messageObj, compareArray, params => {
            if (params) {
              item.submit.content[element] = params;
              count += 1;
            } else {
              return;
            }
          });
        }
      });
      // 全部校验通过
      if (count === formCount) {
        if (item.alterMessage && item.alterMessage.length > 0) {
          this.postFormDataTip(item);
        } else {
          this.postFormData(item);
        }
      }

    } else if (item.action === 'link') {
      this.pageModalService.openPage(item.link);
    } else if (item.action === 'question') {
      // alert
      this.question(item, keys);
    } else if (item.action === 'pageModal') {
      this.pageModalService.openPage(item.link);
    } else if (item.action === 'manageShopping') {
      item.label = item.label === '管理' ? '完成' : '管理';
      // TODO: 交互 显示
      // item.link.params.done
      this.eventService.eventEmit.emit('manageShopping', '1');
    } else if (item.action === 'addressManage') {
      item.label = item.label === '管理' ? '完成' : '管理';
      this.eventService.eventEmit.emit('addressManage', '1');
    } else if (item.action === 'manageShopListTag') {
      item.label = item.label === '管理' ? '完成' : '管理';
      item.label === '管理' ? this.appGlobalService.setCustomBoxVisibility = 'false' : this.appGlobalService.setCustomBoxVisibility = 'true';
      this.eventService.eventEmit.emit('setCustomBoxVisibility', item.label === '管理' ? 'false' : 'true');

    } else if (item.action === 'back') {
      this.close();
    }
  }


  async postFormDataTip(item) {
    const that = this;
    const alert = await this.alertController.create({

      header: '',
      subHeader: '',
      message: item.alterMessage,
      buttons: [{
        text: '取消',
        role: 'cancel',
        cssClass: 'secondary',
        handler: (blah) => {
        }
      }, {
        text: '确定',
        cssClass: 'LJ',
        handler: () => {
          that.postFormData(item);
        }
      }]
    });
    await alert.present();

  }
  postFormData(item) {
    item.submit.sessionId = localStorage.getItem('sessionId');
    console.log('check --> submit', item.submit);
    this.http.post('application/submit', item.submit, res => {
      // 请求成功
      if (res.success) {
        this.success(res, item);
      } else {
        // 请求数据失败
        this.appGlobalService.showToast(res.message, 2000, 'middle');
      }
    });
  }
  success(res, item) {
    this.appGlobalService.delFormData();
    if (res.message) {
      this.appGlobalService.showToast(res.message, 2000, 'middle');
    }
    if (item.back) {
      if (item.submit && item.submit.content
        && item.submit.content.onlyBack !== undefined
        && item.submit.content.onlyBack !== "true") {
        localStorage.setItem("needRefresh", "true");
      } else if (item.submit && item.submit.content && item.submit.content.refresh === 'true') {
        setTimeout(() => {
          this.needRefreshTabByEventEmit();
        }, 500);
      }
      if (Number(item.back) < 0) {
        const back = Math.abs(Number(item.back));
        for (let index = 0; index < back; index++) {
          this.appGlobalService.popTarget();
        }
        this.appGlobalService.goBack(Number(item.back));
        setTimeout(() => {
          if (item.submit && item.submit.content && item.submit.content.tabIndex !== undefined) {
            $('#fixedNavTab' + item.submit.content.tabIndex).click();
          }
        }, 500);
      } else if (Number(item.back) === 0) {
        this.http.reloadCurrentPage();
      } else {
        this.appGlobalService.goBack(Number(item.back));
      }


    }
    else if (res.target) {
      if (res.data && res.data.eventResult && res.params && res.params.eventResult) {
        res.params[res.params.eventResult] = res.data.eventResult;
      }
      const payParams = {
        target: res.target,
        params: res.params ? res.params : {},
        type: res.type
      };
      this.pageModalService.openPage(payParams);

    } else if (res.params && res.params.returnAddressIdKey !== undefined && res.params[res.params.returnAddressIdKey] !== undefined) {
      this.appGlobalService.popTarget();
      // 获取到添加地址成功的 地址id 返回不可以设置刷新上一页
      if (!localStorage.getItem("newAccountAddAddress")) {
        localStorage.setItem("needRefresh", "false");
      }
      const addressItem = {
        id: res.params[res.params.returnAddressIdKey]
      };

      if (res.params.fromAddressList === "1") {
        // 地址列表-> 新增/修改 后返回->列表
        this.eventService.emit("updateAddress", addressItem);
      } else {
        // 发布-> 新增 后返回->发布
        this.eventService.emit("selectAddress", addressItem);
      }

      this.appGlobalService.goBack();

    }

    else if (res.params.fromAddressList === "1") {
      if (!localStorage.getItem("newAccountAddAddress")) {
        localStorage.setItem("needRefresh", "false");
      }

      // 地址列表-> 新增/修改 后返回->列表
      const addressItem = {
        id: res.params['shop_ship_address_id']
      };
      this.appGlobalService.popTarget();
      this.eventService.emit("updateAddress", addressItem);
      this.appGlobalService.goBack();
    }

  }

  scrollEnd(e: any) {
    this.content.ionScrollEnd.subscribe(($event: any) => {
      this.eventService.eventEmit.emit('scrollEnd', $event.currentTarget.offsetTop);
    });
    this.isScrolling = false;
    e.preventDefault();
    // console.log('scrollEnd----->nav1' );
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      // console.log('scrollEnd----->nav1 setTimeout' );
      if (this.appGlobalService.topTop) {
        this.appGlobalService.topTop = false;
        this.content.scrollToTop(200);
      }
    }, 300);
  }
  onScroll(e: any, titleBar?) {
    this.isScrolling = true;
    e.preventDefault();
    if (titleBar && titleBar.onScroll === 'false') {
      // 不处理onScroll内逻辑
      // <!-- 页面title设置 2023年11月8日新增onScroll="false" 返回字符串“false” 表示前端页面不处理滑动事件； 不配置不返回属性  -->
      return;
    }
    let that = this;
    let defaultStr = 'calc(100vh - 8.5rem - env(safe-area-inset-top) - env(safe-area-inset-bottom))';
    let commonTabsNgZorroBox: any;
    let commonTabsNgMainBox: any;
    let commonNgZorroTab: any;
    let hideCssStyleValue: any;
    let currentTabClassName = 'commonNgZorroTab' + this.appGlobalService.ngZorroTabCurrentTabIndex;
    let currentTabHidenStyle = 'hideCssStyleValue' + this.appGlobalService.ngZorroTabCurrentTabIndex;
    //todo 新增直租直售页面tab监听
    if (document.getElementsByClassName('commonTabsNgZorroBox')) {
      this.content.ionScroll.subscribe(($event: any) => {
        // 需要分割滑动的div设置滑动区域
        if (document.getElementsByTagName('app-nav-one')) {
          const navOneCollection = document.getElementsByTagName('app-nav-one') as HTMLCollection;
          for (let i = 0; i < navOneCollection.length; i++) {
            const el = navOneCollection[i];
            if (!this.hasClass(el, 'ion-page-hidden')) {
              commonTabsNgMainBox = el.getElementsByClassName('commonTabsNgMainBox')[0] as HTMLElement;
              commonTabsNgZorroBox = el.getElementsByClassName('commonTabsNgZorroBox')[0] as HTMLElement;
              commonNgZorroTab = el.getElementsByClassName(currentTabClassName)[0] as HTMLElement;
              hideCssStyleValue = el.getElementsByClassName(currentTabHidenStyle)[0] as HTMLElement;
            }
          }
        }
        if (hideCssStyleValue && hideCssStyleValue.value) {
          defaultStr = hideCssStyleValue.value;
        }
        if (commonTabsNgMainBox !== undefined) {
          let absHeight = commonTabsNgMainBox.offsetTop - $event.detail.scrollTop;
          // fixed by andrew.wen for 第一次有误差 误差不超过10个像素
          if (absHeight < 0 && absHeight > -10) {
            absHeight = Math.abs(absHeight);
          }

          if (document.getElementById(commonTabsNgZorroBox.id) && absHeight <= 10 && !that.isStickyDiv1) {
            commonTabsNgZorroBox.style.position = "sticky";
            commonTabsNgZorroBox.style.top = "0px";
            that.isStickyDiv1 = true;
            if (this.showScrollToTopBtnTemp) {
              this.showScrollToTopBtn = this.showScrollToTopBtnTemp;
            }
            if (this.needScrollToTopHiddenImg && this.titleBar.headerBgStyle && this.titleBar.headerStyle) {
              this.titleBar.headerBgStyle = '';
              this.titleBar.headerStyle = '';
            }
          } else if (document.getElementById(commonTabsNgZorroBox.id) && absHeight > 10 && that.isStickyDiv1) {
            that.isStickyDiv1 = false;
            commonTabsNgZorroBox.style.removeProperty('position');
            commonTabsNgZorroBox.style.removeProperty('top');
            this.showScrollToTopBtn = false;
            console.log('下拉', '2');
            if (this.needScrollToTopHiddenImg && this.headerBgStyle && this.headerStyle) {
              this.titleBar.headerBgStyle = this.headerBgStyle;
              this.titleBar.headerStyle = this.headerStyle;
            }
          }
        }
      });
    }
    // 导航全透明滑动变化
    // <!-- titleBar 增加属性  headerId  、customBgStyle， customBg（要支持富文本），
    // 滑动前样式原有headerStyle，background （作用于toolbar),  新增 toolbarStyle 
    // 滑动后要改变样式用到：新增： headerChangeStyle ,toolbarChangeStyle
    // 共新增 6个属性  -->
    if (this.titleBar && this.titleBar.headerId && document.getElementById('home-header-bg-box' + this.titleBar.headerId) && this.titleBar.fullscreen) {
      this.content.ionScroll.subscribe(($event: any) => {
        const ionHeader = document.getElementById('home-header-bg-box' + this.titleBar.headerId) as HTMLElement;
        const ionToolbar = document.getElementById('superToolbar' + this.currentRootTabId) as HTMLElement;
        if ($event.detail.scrollTop > 64 && !that.isHearderDivInConent) {
          console.log('onScroll:__fullscreen' + $event.detail.scrollTop);
          that.isHearderDivInConent = true;
          try {
            if (this.titleBar.headerChangeStyle && this.titleBar.toolbarChangeStyle) {
              ionHeader.setAttribute("style", this.titleBar.headerChangeStyle);
              ionToolbar.setAttribute("style", this.titleBar.toolbarChangeStyle);

            } else {
              ionHeader.setAttribute("style", "background:white;position:fixed;z-index: 10000;");
              ionToolbar.setAttribute("style", "--background:white;padding-top:constant(safe-area-inset-top)");

            }
            // title
            if (ionToolbar.children && ionToolbar.children.length > 0 && this.titleBar.title) {
              const that = this;
              $("#" + 'superToolbar' + this.currentRootTabId).children().each(function (i, e) {

                if (e.id == "nav-title") {
                  if (that.titleBar.title.changeCssStyle) {
                    e.setAttribute("style", that.titleBar.title.changeCssStyle);
                  } else {
                    // e.setAttribute("style", "font-size: 1.13rem;font-weight: bold;padding: unset !important;color: #0f0f0f;");
                  }
                }
              });

            }

          } catch (error) {

          }
        } else if ($event.detail.scrollTop <= 64 && that.isHearderDivInConent) {
          try {
            that.isHearderDivInConent = false;
            if (this.titleBar.headerStyle && this.titleBar.toolbarStyle) {
              ionHeader.setAttribute("style", this.titleBar.headerStyle);
              ionToolbar.setAttribute("style", this.titleBar.toolbarStyle);

            } else {
              ionHeader.setAttribute("style", "background:transparent;position:fixed;z-index: 10000;backdrop-filter:unset;");
              ionToolbar.setAttribute("style", "--background:transparent;padding-top:constant(safe-area-inset-top)");

            }
            // title
            if (ionToolbar.children && ionToolbar.children.length > 0 && this.titleBar.title) {
              const that = this;
              $("#" + 'superToolbar' + this.currentRootTabId).children().each(function (i, e) {

                if (e.id == "nav-title") {
                  if (that.titleBar.title.cssStyle) {
                    e.setAttribute("style", that.titleBar.title.cssStyle);
                  } else {
                    // e.setAttribute("style", "font-size: 1.13rem;font-weight: bold;padding: unset !important;color: transparent;");
                  }
                }
              });
            }

          } catch (error) {

          }
        }
      })

    }

    // todo 新增筛选组件监听
    if (document.getElementById('filterTransverseTag')) {
      this.content.ionScroll.subscribe(($event: any) => {
        console.log('onScroll:' + $event.detail.scrollTop);
        // document.getElementsByTagName('app-nav-one')[1].getElementsByClassName('scroll-box');

        let absHeight = $event.detail.scrollTop - document.getElementById("filterTransverseTag").offsetTop;
        // fixed by andrew.wen for 第一次有误差 误差不超过10个像素
        if (absHeight < 0 && absHeight > -10) {
          absHeight = Math.abs(absHeight);
        }
        if (document.getElementById("filterTransverseTag") && absHeight >= 0) {
          if (window['navOneListenerScroll'] && window['navOneListenerScroll'] === '1') {
            return;
          }
          if ($event.detail.scrollTop - document.getElementById("filterTransverseTag").offsetTop > 45) {
            // this.appGlobalService.openBackdrop = false;
          }
          const tabBarLocation = document.getElementById('filterOpenAllButton');
          if (tabBarLocation) {
            const buttonNav = tabBarLocation as HTMLElement;
            buttonNav.style.width = "100vw";
            buttonNav.style.height = "2.5rem";
            buttonNav.style.position = "sticky";
            buttonNav.style.background = "white";
            buttonNav.style.top = "0px";
            buttonNav.style.zIndex = "13";
            buttonNav.style.display = 'flex';

            // 需要分割滑动的div设置滑动区域
            if (document.getElementsByTagName('app-nav-one')) {
              const navOneCollection = document.getElementsByTagName('app-nav-one') as HTMLCollection;
              for (let i = 0; i < navOneCollection.length; i++) {
                const el = navOneCollection[i];
                if (!this.hasClass(el, 'ion-page-hidden')) {
                  const splitDiv = el.getElementsByClassName('scroll-box')[0] as HTMLElement;
                  // splitDiv.style.height = this.content['el']['clientHeight'] - 45 + 'px';
                  // splitDiv.style.overflow = 'scroll';
                  // splitDiv.style.scrollBehavior = 'smooth';
                }
              }
            }
          }
          document.getElementById('filterTransverseTag').style.display = 'none';
          if (document.getElementById('filterExpendAllButton') && document.getElementById('filterExpendAllButton').style.display === '') {
            document.getElementById('filterExpendAllButton').style.display = 'none'
          }
        } else {
          const tabBarLocation = document.getElementById('filterOpenAllButton');
          if (tabBarLocation) {
            const buttonNav = tabBarLocation as HTMLElement;
            buttonNav.style.removeProperty("position");
            buttonNav.style.removeProperty("top");
            buttonNav.style.display = 'none';

            // 需要分割滑动的div设置滑动区域
            if (document.getElementsByTagName('app-nav-one')) {
              const navOneCollection = document.getElementsByTagName('app-nav-one') as HTMLCollection;
              for (let i = 0; i < navOneCollection.length; i++) {
                const el = navOneCollection[i];
                if (!this.hasClass(el, 'ion-page-hidden')) {
                  const splitDiv = el.getElementsByClassName('scroll-box')[0] as HTMLElement;
                  splitDiv.style.removeProperty('height');
                  splitDiv.style.removeProperty('overflow');
                  splitDiv.style.removeProperty('scroll-behavior');
                }
              }
            }
          }
        }
      });
    }


    // 2023.05.05 蜂喔用户更新地址 如果配置了cssType 则用这种方式处理

    if (document.getElementById('tabBarLocation')) {
      let tabBarLocation = document.getElementById('tabBarLocation');
      tabBarLocation.style.position = "sticky";
      tabBarLocation.style.top = "0";
      tabBarLocation.style.zIndex = "13";
    }



    // todo 原铺铺旺新增的监听
    if (document.getElementById('scrollContent')) {
      this.content.ionScroll.subscribe(($event: any) => {
        console.log('onScroll:' + $event.detail.scrollTop);
        this.eventService.eventEmit.emit('onScroll', $event.detail.scrollTop);
        // 详情页
        // const customerDetails = document.getElementById("customer_details_hid");
        // if (customerDetails) {
        //   // 手机盒子高度
        //   let contentBoxHeight;
        //   if (window.innerHeight) {
        //     contentBoxHeight = window.innerHeight;
        //   } else if (document.documentElement.clientHeight) {
        //     contentBoxHeight = document.documentElement.clientHeight;
        //   }
        //   // 页面与盒子高差
        //   const heightDiffer = customerDetails.scrollHeight - contentBoxHeight;
        //   if ($event.detail.scrollTop > heightDiffer + 30) {
        //     if (document.getElementById('customer_details_scroll_id')) {
        //       document.getElementById('customer_details_scroll_id').style.display = 'block';
        //     }
        //   } else {
        //     if (document.getElementById('customer_details_scroll_id')) {
        //       document.getElementById('customer_details_scroll_id').style.display = 'none';
        //     }
        //   }
        // }

        if (document.getElementById('scrollContent') &&
          $event.detail.scrollTop - 44 >= document.getElementById('scrollContent').offsetTop) {

          // add by andrew.wen for 样式优化
          // if (document.getElementById('sg-bg')) {
          //   document.getElementById('sg-bg').style.display = "block";
          // }
          const tab2Collection = document.getElementsByTagName('app-nav-one')[0].getElementsByClassName('buttonNavThreeClassName');
          if (tab2Collection && tab2Collection.length > 0) {
            const buttonNav = tab2Collection[0] as HTMLElement;
            buttonNav.style.position = "sticky";
            buttonNav.style.position = "-webkit-sticky";
            buttonNav.style.background = "white";
            buttonNav.style.top = "0";
            buttonNav.style.marginTop = "0"; // # 适配vivo x27手机上展示少了一个像素
            setTimeout(() => { buttonNav.style.zIndex = "13"; }, 200);
          }
          // document.getElementById('topSegment').style.position = "sticky";
          // document.getElementById('topSegment').style.position = "-webkit-sticky";
          // document.getElementById('topSegment').style.top = "0";
          // setTimeout(() => { document.getElementById('topSegment').style.zIndex = "13"; }, 200);
          // this.isHeader = false;
        } else {
          if (document.getElementById('homeTopTab')) {
            document.getElementById('homeTopTab').style.display = "block";
          }
          if (document.getElementsByTagName('app-nav-one') && document.getElementsByTagName('app-nav-one')[0]) {
            const tab2Collection = document.getElementsByTagName('app-nav-one')[0].getElementsByClassName('buttonNavThreeClassName');
            if (tab2Collection && tab2Collection.length > 0) {
              const buttonNav = tab2Collection[0] as HTMLElement;
              buttonNav.style.removeProperty('position');
              buttonNav.style.removeProperty('top');
              buttonNav.style.removeProperty('z-index');
            }
          }
          // document.getElementById('sg-bg').style.display = "none";
          // document.getElementById('topSegment').style.removeProperty('position');
          // document.getElementById('topSegment').style.removeProperty('top');
          // document.getElementById('topSegment').style.removeProperty('z-index');
          this.isHeader = true;
        }
      });
    }

    // todo 直租直售
    if (document.getElementById('bottomSearch')) {
      this.content.ionScroll.subscribe(($event: any) => {
        try {

          // 需要分割滑动的div设置滑动区域
          if (document.getElementsByTagName('app-nav-one')) {
            const navOneCollection = document.getElementsByTagName('app-nav-one') as HTMLCollection;
            let searchButtonRight;
            let bottomSearch;
            for (let i = 0; i < navOneCollection.length; i++) {
              const el = navOneCollection[i];
              if (!this.hasClass(el, 'ion-page-hidden')) {
                searchButtonRight = el.getElementsByClassName('searchButtonRight')[0] as HTMLElement;
                bottomSearch = el.getElementsByClassName('bottomSearchBox')[0] as HTMLElement;
                break;
              }
            }
            if ($event.detail.scrollTop > 44 && !that.isSearchBottomDiv1) {
              that.isSearchBottomDiv1 = true;
              if (bottomSearch) {
                bottomSearch.style.display = 'none';
              }
              if (searchButtonRight) {
                searchButtonRight.style.display = 'flex'
              }
            } else if ($event.detail.scrollTop <= 44 && that.isSearchBottomDiv1) {
              that.isSearchBottomDiv1 = false;
              if (bottomSearch) {
                bottomSearch.style.display = 'block';
              }
              if (searchButtonRight) {
                searchButtonRight.style.display = 'none';
              }
            }
          }
        } catch (error) {

        }
      });
    }




  }


  updateFooterChange(obj, index?) {
    if (obj !== undefined && obj.partLink !== undefined) {
      this.http.post('application/part',
        {
          viewId: obj.partLink.target,
          sessionId: localStorage.getItem("sessionId"),
          params: obj.partLink.params
        }, (res: any) => {
          if (res !== undefined && res != null) {
            this.tabsService.getPageData(res, pageData => {
              this.coms = pageData.coms;
              this.footerComs = pageData.footerComs;
            });

          }
        });
    }
  }


  // 点击遮罩层关闭下拉面板
  backdropclick() {
    this.openBackdrop = false;
    this.appGlobalService.openBackdrop = false;


    this.eventService.eventEmit.emit('tagBoxStyle', 1);

    // 蜂喔商户 1.6.25 
    if (this.appGlobalService['type30PanelDivId']) {
      let tempDivId = this.appGlobalService['type30PanelDivId'];
      if (document.getElementById(tempDivId)) {
        const header = document.getElementById(tempDivId).children[0] as HTMLElement;
        header.click();
      }
    }

    if (this.switchBlockTagClassNameType === 1) {
      if ($('.switch-main-box-newCss2')) {
        $('.switch-main-box-newCss2').show();
        $('.switch-main-box-newCss-bottom2').hide(100);
      }
    } else {
      if ($('.switch-main-box-newCss')) {
        $('.switch-main-box-newCss').show();
        $('.switch-main-box-newCss-bottom').hide(100);
      }
    }

  }
  // 刷新当前页
  refreshPage() {
    clearTimeout(this.timer)
    const that = this;
    this.timer = setTimeout(() => {
      that.getInitInfo(0);
    });
  }
  // 刷新列表事件
  refreshData(event) {


    let that = this;
    event.target.complete();
    const nowTime = new Date().getTime() / 1000; // 指定毫秒数内不刷新
    if (nowTime - this.refreshDataTime > this.refreshDelayTime) {
      that.eventService.eventEmit.emit('checkListIsShowRefresher', '1');
    }
  }


  async customSegmentChanged(e: any) {
    const index = e.detail.value;
    const segmentButton = this.segment.nativeElement.children[index];
    segmentButton.scrollIntoView({
      behavior: "smooth",
      inline: "center",
      block: "nearest",
    });
    if (this.subTagData.data) {
      this.http.post(
        "application/part",
        {
          viewId: this.subTagData.data[index].partLink.target,
          sessionId: localStorage.getItem("sessionId"),
          params: this.subTagData.data[index].partLink.params,
        },
        (res: any) => {
          // #616 修改：点击转让服务和选址服务跳到第一屏的画面
          this.content.scrollToTop(0);
          if (res !== undefined && res != null) {
            setTimeout(() => {
              this.subTagData.currentData = JSON.parse(res.script);
              localStorage.setItem(
                "refreshGrayBgTag",
                "" + this.subTagData.currentData.isGrayBg
              );
              this.eventService.eventEmit.emit(
                "refreshGrayBg",
                "refreshGrayBg"
              );
              localStorage.setItem("dataMapFixedTabContainer", JSON.stringify(this.subTagData));
              this.eventService.eventEmit.emit('refreshNav1FixedContainer', 'refreshNav1FixedContainer');
            }, 50);
          }
        }
      );

    }
  }

  goPage(item) {
    if (item.params && item.params.key && item.params.key.code) {
      item.params[item.params.key.code] = item.params.key.codes.split(',')[this.idx - 1];
    } else if (item.params.key.codes) {
      item.params.key.code = item.params.key.codes.split(',')[this.idx - 1];
      item.params.code = item.params.key.code;
    }

    this.pageModalService.openPage(item);
  }


  async segmentChanged(e: any) {
    const index = e.detail.value;
    const segmentButton = this.segment.nativeElement.children[index];
    segmentButton.scrollIntoView({
      behavior: "smooth",
      inline: "center",
      block: "nearest",
    });
    if (this.tagData.data) {
      this.tagData.currentTab = index;
      if (localStorage.getItem("topTapPart" + index)) {
        const parseData = JSON.parse(
          localStorage.getItem("topTapPart" + index)
        );
        this.tagData.currentData = parseData;
        localStorage.setItem(
          "refreshGrayBgTag",
          "" + this.tagData.currentData.isGrayBg
        );
        this.eventService.eventEmit.emit("refreshGrayBg", "refreshGrayBg");
        setTimeout(() => {
          localStorage.setItem(
            "dataMapTopTabContainer",
            JSON.stringify(this.tagData)
          );
          this.eventService.eventEmit.emit(
            "refreshTopTabContainer",
            "refreshTopTabContainer"
          );
          this.content.scrollToTop(0);
        }, 200);
      } else {
        this.http.post(
          "application/part",
          {
            viewId: this.tagData.data[index].partLink.target,
            sessionId: localStorage.getItem("sessionId"),
            params: this.tagData.data[index].partLink.params,
          },
          (res: any) => {
            // #616 修改：点击转让服务和选址服务跳到第一屏的画面
            this.content.scrollToTop(0);
            if (res !== undefined && res != null) {
              setTimeout(() => {
                this.tagData.currentData = JSON.parse(res.script);
                localStorage.setItem(
                  "refreshGrayBgTag",
                  "" + this.tagData.currentData.isGrayBg
                );
                this.eventService.eventEmit.emit(
                  "refreshGrayBg",
                  "refreshGrayBg"
                );
                localStorage.setItem(
                  "dataMapTopTabContainer",
                  JSON.stringify(this.tagData)
                );
                this.eventService.eventEmit.emit(
                  "refreshTopTabContainer",
                  "refreshTopTabContainer"
                );
              }, 50);
            }
          }
        );
      }
    }
  }
  ionViewDidEnter() {
    this.eventService.eventEmit.emit("updateFrom" + localStorage.getItem('currentPath'), "true");
  }

  ionViewWillEnter() {
    console.log("navonevc ionViewWillEnter");
    // 2.2.19 refresh view tree
    // this.appGlobalService.refreshViewTree(this.content);
    // 蜂喔赚钱宝1.7.1 新增参数用于初始化tab切换
    // this.appGlobalService.headerTopTabIndex = 0;
    if (this.eventService.eventEmit.listenerCount('TOTOP') > 0) {
      this.eventService.eventEmit.removeListener('TOTOP');
    }
    this.eventService.eventEmit.on("TOTOP", (obj) => {

      // console.log("TOTOP nav1");
      if (this.isScrolling) {
      } else {
        this.appGlobalService.topTop = false;
        this.content.scrollToTop(200);
      }
    });



    setTimeout(() => {
      if (document.getElementById("fixedNavTab0") && localStorage.getItem('currentPath').indexOf('nav2') === -1) {
        if (this.appTypeCustom !== 'LJ') {
          this.getInitInfo(0);
        }
      } else if (document.getElementById("btNavDefaultTab0") && localStorage.getItem('currentPath').indexOf('nav2') === -1) {
        if (this.appTypeCustom !== 'LJ') {
          this.getInitInfo(0);
        }
      }
    }, 0);

    // 这样判断太耗费性能
    // if (this.appTypeCustom === "LJ"
    //   && localStorage.getItem("leavePageFromDetail")
    //   && localStorage.getItem("leavePageFromDetail") === 'true') {
    //   localStorage.removeItem("leavePageFromDetail");
    //   this.getInitInfo(0);
    // }
    if (this.slides) {
      this.slides.startAutoplay()
    }
    if (this.slides2) {
      this.slides2.stopAutoplay();
    }

  }

  // ionViewWillLeave() {
  // 如果是从详情页面跳转到新的页面记录下
  // if (this.appTypeCustom === "LJ" && localStorage.getItem('isDetailPage') && localStorage.getItem('isDetailPage') === 'true') {
  //   localStorage.setItem("leavePageFromDetail", "true");
  // }
  // this.appGlobalService.globalTempEvent
  //   console.log('navone.component.leave------');
  // }

  ionViewWillLeave() {


    this.pageModalService.closeAllModal();// 2024.01.05 返回弹窗没有关闭
    if (this.appGlobalService.openBackdrop === true) {
      this.appGlobalService.openBackdrop = false;
    }
    if (this.appTypeCustom === "LJ") {
      if (this.appGlobalService.needHiddenId) {
        this.appGlobalService.openBackdrop = false;
        const tagBox = document.getElementById(this.appGlobalService.needHiddenId) as HTMLElement;
        if (tagBox) {
          tagBox.style.display = 'block';
        }
      }
    }
    if (this.slides) {
      this.slides.stopAutoplay()
    }

    if (this.slides2) {
      this.slides2.startAutoplay();
    }
    // 富文本工具栏
    if (document.getElementById("toolbar-" + this.currentRootTabId)) {
      document.getElementById("toolbar-" + this.currentRootTabId).classList.add('displayno');
    }
  }


  switchBlockClick(item, className, data, i) {
    try {
      const array = document.getElementsByClassName('switch-box-button-' + className);


      if (item.needCheckTabName && item.params && item[item.needCheckTabName]) {
        this.appGlobalService.needCheckTabName = item.needCheckTabName;
        this.appGlobalService[item.needCheckTabName] = item[item.needCheckTabName];
        console.log('needCheckTabName===', this.appGlobalService[item.needCheckTabName]);
      }


      if (className === 'newCss' || className === 'newCss2') {
        if (this.appGlobalService.openBackdrop) {
          if (className === 'newCss2') {
            $('.switch-main-box-newCss2').show();
            $('.switch-main-box-newCss-bottom2').hide(100);
          } else {
            $('.switch-main-box-newCss').show();
            $('.switch-main-box-newCss-bottom').hide(100);
          }
          this.appGlobalService.openBackdrop = false;
          if (this.switchBlockTag !== undefined && this.switchBlockTag.data !== undefined) {
            // 2023年新增收起时自动滑动到指定的div
            for (let index = 0; index < this.switchBlockTag.data.length; index++) {
              const element = this.switchBlockTag.data[index];
              if (element.selected === 'true') {
                // $('.switch-box-newCss').css('transform', 'translate3d(-' + 3 * index + 'rem, 0px, 0px)');
                if (document.getElementById(className === 'newCss2' ? 'newCss2' + this.switchNewCssBtnId : '' + this.switchNewCssBtnId)) {
                  document.getElementById(className === 'newCss2' ? 'newCss2' + this.switchNewCssBtnId : '' + this.switchNewCssBtnId).children[i].scrollIntoView({
                    behavior: "smooth",
                    inline: "center",
                    block: "nearest",
                  });
                }
                break;
              }
            }
          }
        }

        // 2024.06.11 2.3.3 fixed selected tab link
        if (item.disableSelectedStyle !== undefined && item.disableSelectedStyle === 'true') {
          if (item.action !== undefined && item.action === 'link') {
            this.pageModalService.openPage(item.link);
          }
        } else {
          data.forEach((e, index) => {
            e['selected'] = '';
            const btnId = e.id;
            if (item.id === btnId) {

              let requestParam = { filter: item.params };
              if (item.plugin_type_id) {
                requestParam = Object.assign({ plugin_type_id: item.plugin_type_id }, { filter: item.params });
              }
              if (item.action !== undefined && item.action === 'link') {
                this.pageModalService.openPage(item.link);
              } else {
                if (item.listTagName) {
                  const emitStr = item.listTagName + 'AskForList';
                  if (item.params === undefined) {
                    item.params = { content: {} };
                  }
                  localStorage.setItem(emitStr + 'Tag', '1');
                  this.eventService.eventEmit.emit(emitStr, item.params);
                } else {
                  this.requestData(item, requestParam);
                }
              }
            }
          });
          item['selected'] = 'true';
        }



      } else {
        item.selected = 'true';
        for (let index = 0; index < array.length; index++) {
          const element = array[index];
          const btnId = element.id;
          if (item.id === btnId) {
            if (!this.hasClass(element, 'switch-checked-' + className)) {
              this.addClass(element, "switch-checked-" + className);
              this.addClass(element.children[0], "switch-box-label-checked-" + className);
              let requestParam = { filter: item.params };
              if (item.plugin_type_id) {
                requestParam = Object.assign({ plugin_type_id: item.plugin_type_id }, { filter: item.params });
              }
              if (item.listTagName) {
                const emitStr = item.listTagName + 'AskForList';
                if (item.params === undefined) {
                  item.params = { content: {} };
                }
                localStorage.setItem(emitStr + 'Tag', '1');
                this.eventService.eventEmit.emit(emitStr, item.params);
              } else {
                this.requestData(item, requestParam);
              }
            }
          } else {
            this.removeClass(element, "switch-checked-" + className);
            this.removeClass(element.children[0], "switch-box-label-checked-" + className);
          }
        }
      }

      // if (item.params.plugin_type_id) {
      // this.currentSwitchBlockPluginId = item.params.plugin_type_id;
      // this.isShowSiftCondition = false;
      // }
    } catch (error) {

    }
  }

  requestData(item, requestParam?) {
    let that = this;
    try {
      if (this.isRefreshAfterCLickSwitchButton) {

        if (this.refreshFilterId !== null) {
          const params = {
            content: item.params, // { filter: this.result.filter },
            id: this.refreshFilterId,
            sessionId: localStorage.getItem("sessionId")
          };
          this.http.post("application/submit", params, res => {
            if (res) {
              res.data.filterItems.forEach(element => {
                if (element.cssStyle) {
                  const cssStyles = element.cssStyle.split(";");
                  element.ngStyle = {};

                  for (let i = 0; i < cssStyles.length; i++) {
                    const cssStrs = cssStyles[i].split(":");
                    if (cssStrs[0].trim() !== "") {
                      element.ngStyle[cssStrs[0]] = cssStrs[1];
                    }
                  }
                }
              });
              // this.footerComs[0].tagData.data = res.data.filterItems;
              // that.footerComs = null;
              // that.footerComs.forEach(element => {
              //   element.tagData.data = res.data.filterItems;
              // });
              if (res.data.filterItems[0] !== undefined) {
                that.footerComs[0].tagData.data[0].label = res.data.filterItems[0].label;
                that.footerComs[0].tagData.data[0].disabled = res.data.filterItems[0].disabled;
                that.footerComs[0].tagData.data[0].paramName = res.data.filterItems[0].paramName;
                that.footerComs[0].tagData.data[0].link = res.data.filterItems[0].link;
                that.footerComs[0].tagData.data[0].cssStyle = res.data.filterItems[0].cssStyle;
                that.footerComs[0].tagData.data[0].cssColor = res.data.filterItems[0].cssColor;
                that.footerComs[0].tagData.data[0].round = res.data.filterItems[0].round;
                that.footerComs[0].tagData.data[0].plain = res.data.filterItems[0].plain;
              }

            }
            // setTimeout(() => {
            that.message.sendMessage(requestParam);
            // }, 1000);
          }, err => {
            console.log('error----->' + JSON.stringify(err));
            // this.firstLevelList = this.secondLevelList = []; // 初始化
          });
        } else {
          this.message.sendMessage(requestParam);
          // this.getResult({ active: true, displayName: '', value: this.result.filter[this.key] });
        }

      } else {
        this.message.sendMessage(requestParam);
      }



    } catch (error) {
    }

  }


  /**
   * 添加class
   */
  addClass(ele, value) {
    if (value) {
      let curValue = this.getClass(ele);
      if (curValue.indexOf(value) === -1) {
        curValue = curValue + " " + value;
      }
      ele.setAttribute("class", curValue.trim());
    }
  }
  /**
   * 删除class
   */
  removeClass(ele, value) {
    if (value) {
      let curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        curValue = (" " + curValue + " ").replace(" " + value + " ", " ");
      }
      ele.setAttribute("class", curValue.trim());
    }
  }
  /**
   * 元素是否存在值为@{value}的class
   */
  hasClass(ele, value) {
    let has = false;
    if (value) {
      const curValue = this.getClass(ele);
      if (curValue.indexOf(value) > -1) {
        has = true;
      }
    }
    return has;
  }

  /**
   * 获取class
   */
  getClass(elem) {
    return elem.getAttribute && elem.getAttribute("class") || "";
  }
  // 滑动到顶部 
  scrollToTop(event) {
    event.stopPropagation();
    this.content.scrollToTop(1000);
  }

  async presentPopover(ev: any, data) {
    const popover = await this.popoverController.create({
      component: PopoverComponent,
      cssClass: 'rightAndTop',
      event: ev,
      mode: 'ios',
      animated: true,
      showBackdrop: false,
      translucent: true,
      componentProps: { tagData: data }
    });
    await popover.present();
    const { role } = await popover.onDidDismiss();
    console.log('onDidDismiss resolved with role', role);
  }
  search(event) {
    if (event && event.keyCode !== 13) {
      return;
    } else {
      this.textButton(this.titleBar.textButton, this.titleBar.searchInput);
    }
  }

  tabClick(id, i) {
    setTimeout(() => {
      this.appGlobalService.headerTopTabIndex = i;
    }, 0);
    $('#' + id).click();
  }

  ngOnDestroy(): void {
    console.log('ngOnDestroy disableBackConfig = ' + localStorage.getItem('disableBackConfig'));
    //2024.01.29 参数防止没有删除
    if (localStorage.getItem('disableBackConfig') !== null) {

    }
    setTimeout(() => {
      // 蜂喔赚钱宝1.7.1 离开页面时需要清除底部按钮的状态
      this.appGlobalService.footerButton = undefined;
      this.appGlobalService.headerTopTabIndex = 0;
      this.appGlobalService.headerTopTab = undefined;
      this.appGlobalService.setCustomBoxVisibility = undefined;
    }, 0);
    console.log('ngOnDestroy this.switchBlockTag=', this.switchBlockTag)
  }
  gotoEnterpriseWechat(e) { }

  selectAddress() {

    if (this.eventService.eventEmit.listenerCount('selectAddress') > 0) {
      this.eventService.eventEmit.removeListener('selectAddress');
    }

    const that = this;
    this.eventService.eventEmit.on('selectAddress', item => {
      this.forward.params[this.forward.params['returnAddressIdKey']] = item.id;

      console.log('接受选择的地址id:' + JSON.stringify(item));
      this.refreshPage();
    });
  }

  showTipBox(type) {
    this.appGlobalService.showTipBox(type);
  }
  // 新增选择城市
  async changeCity(item, event?) {
    if (event !== undefined) {
      event.stopPropagation();
    }
    if (item.link.params && item.link.params.disableClickLabel !== undefined) {
      this.pageModalService.openPage(item.link);
      return;
    }

    const that = this;
    let changeCityTarget = item.link.target;
    if (item.link.params && item.link.params.changeCityPageTarget !== undefined) {
      changeCityTarget = item.link.params.changeCityPageTarget;
    }
    const modal = await this.modalController.create({
      component: ChooseCityComponent,
      componentProps: { value: changeCityTarget, noStorage: true, entryType: 1, modalTitle: "选择城市" }, //    首页是1 默认不传或者0
    });
    modal.onDidDismiss().then((data) => {
      const value = data.data;
      if (value !== undefined && value !== undefined) {
        if (value.name) {
          this.areaPositionInfo = value;
          const targetObj = JSON.parse(localStorage.getItem('targetObj'));
          if (targetObj && targetObj.bat && targetObj.bat.length > 0) {
            targetObj.forward = targetObj.bat[targetObj.bat.length - 1];
            if (targetObj.forward && targetObj.forward.params && targetObj.forward.params.code) {
              targetObj.forward.params.code = this.areaPositionInfo.code;
              if (targetObj.forward.params.useAreaPoint !== undefined) {
                targetObj.forward.params.latitude = this.areaPositionInfo.center.lat;
                targetObj.forward.params.longitude = this.areaPositionInfo.center.lng;
              } else {
                if (targetObj.forward.params.useCurrentPointForDistance !== undefined) {
                  targetObj.forward.params.latitude = JSON.parse(localStorage.getItem('currentCityPosition')).center.lat;
                  targetObj.forward.params.longitude = JSON.parse(localStorage.getItem('currentCityPosition')).center.lng;
                } else {
                  targetObj.forward.params.latitude = this.positionInfo.center.lat;
                  targetObj.forward.params.longitude = this.positionInfo.center.lng;
                }
              }

              // 2.0 后台最新加参数
              if (this.areaPositionInfo.center.lat && this.areaPositionInfo.center.lng) {
                targetObj.forward.params['location'] = { latitude: 0.0, longitude: 0.0 };
                targetObj.forward.params['location'].latitude = this.areaPositionInfo.center.lat;
                targetObj.forward.params['location'].longitude = this.areaPositionInfo.center.lng;
              }
              localStorage.setItem('targetObj', JSON.stringify(targetObj));
            }
          }
          this.appGlobalService.reloadCurrentPage(500);
        }
      }
    });
    return await modal.present();
  }

  downArrowClick() {
    if (this.switchBlockTagClassNameType === 1) {
      $('.switch-main-box-newCss2').hide();
      $('.switch-main-box-newCss-bottom2').fadeIn();
    } else {
      $('.switch-main-box-newCss').hide();
      $('.switch-main-box-newCss-bottom').fadeIn();
    }
    this.appGlobalService.openBackdrop = true;
    // console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  	downArrowClick   ', '  	1   ');
  }

  upArrowClick() {
    if (this.switchBlockTagClassNameType === 1) {
      $('.switch-main-box-newCss2').show();
      $('.switch-main-box-newCss-bottom2').hide(100);
    } else {
      $('.switch-main-box-newCss').show();
      $('.switch-main-box-newCss-bottom').hide(100);
    }
    this.appGlobalService.openBackdrop = false;
    console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  	upArrowClick   ', '  	1   ');
    if (this.switchBlockTag !== undefined && this.switchBlockTag.data !== undefined) {
      console.log('this.switchBlockTag 36')
      // 2023年新增收起时自动滑动到指定的div
      for (let index = 0; index < this.switchBlockTag.data.length; index++) {
        const element = this.switchBlockTag.data[index];
        if (element.selected === 'true') {
          // $('.switch-box-newCss').css('transform', 'translate3d(-' + 3 * index + 'rem, 0px, 0px)');
          if (document.getElementById(this.switchNewCssBtnId)) {
            document.getElementById(this.switchNewCssBtnId).children[index].scrollIntoView({
              behavior: "smooth",
              inline: "center",
              block: "nearest",
            });
          }
          break;
        }
      }
    }
  }

  btnOnload() {
    console.log(new Date().toLocaleString() + '.' + new Date().getMilliseconds() + '  	加载完成！  ', '  	   ');
  }
}



